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 int|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($owner, $rel, $module, $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;
182 // When we hide our friends we will only show the pure number but don't allow more.
183 $show_contacts = empty($owner['hide-friends']);
185 // Allow fetching the contact list when the requester is part of the list.
186 if (($owner['page-flags'] == User::PAGE_FLAGS_PRVGROUP) && !empty($requester)) {
187 $show_contacts = DBA::exists('contact', ['nurl' => Strings::normaliseLink($requester), 'uid' => $owner['uid'], 'blocked' => false]);
190 if (!$show_contacts) {
195 $data['first'] = DI::baseUrl() . $modulePath . $owner['nickname'] . '?page=1';
197 $data['type'] = 'OrderedCollectionPage';
200 $contacts = DBA::select('contact', ['url'], $condition, ['limit' => [($page - 1) * 100, 100]]);
201 while ($contact = DBA::fetch($contacts)) {
202 $list[] = $contact['url'];
204 DBA::close($contacts);
207 $data['next'] = DI::baseUrl() . $modulePath . $owner['nickname'] . '?page=' . ($page + 1);
210 $data['partOf'] = DI::baseUrl() . $modulePath . $owner['nickname'];
212 $data['orderedItems'] = $list;
219 * Public posts for the given owner
221 * @param array $owner Owner array
222 * @param integer $page Page number
223 * @param string $requester URL of requesting account
225 * @return array of posts
226 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
227 * @throws \ImagickException
229 public static function getOutbox($owner, $page = null, $requester = '')
231 $condition = ['private' => [Item::PUBLIC, Item::UNLISTED]];
233 if (!empty($requester)) {
234 $requester_id = Contact::getIdForURL($requester, $owner['uid']);
235 if (!empty($requester_id)) {
236 $permissionSets = DI::permissionSet()->selectByContactId($requester_id, $owner['uid']);
237 if (!empty($permissionSets)) {
238 $condition = ['psid' => array_merge($permissionSets->column('id'),
239 [DI::permissionSet()->selectPublicForUser($owner['uid'])])];
244 $condition = array_merge($condition,
245 ['uid' => $owner['uid'],
246 'author-id' => Contact::getIdForURL($owner['url'], 0, false),
247 'gravity' => [GRAVITY_PARENT, GRAVITY_COMMENT],
248 'network' => Protocol::FEDERATED,
249 'parent-network' => Protocol::FEDERATED,
254 $count = Post::count($condition);
256 $data = ['@context' => ActivityPub::CONTEXT];
257 $data['id'] = DI::baseUrl() . '/outbox/' . $owner['nickname'];
258 $data['type'] = 'OrderedCollection';
259 $data['totalItems'] = $count;
262 $data['first'] = DI::baseUrl() . '/outbox/' . $owner['nickname'] . '?page=1';
264 $data['type'] = 'OrderedCollectionPage';
267 $items = Post::select(['id'], $condition, ['limit' => [($page - 1) * 20, 20], 'order' => ['created' => true]]);
268 while ($item = Post::fetch($items)) {
269 $activity = self::createActivityFromItem($item['id'], true);
270 $activity['type'] = $activity['type'] == 'Update' ? 'Create' : $activity['type'];
272 // Only list "Create" activity objects here, no reshares
273 if (!empty($activity['object']) && ($activity['type'] == 'Create')) {
274 $list[] = $activity['object'];
280 $data['next'] = DI::baseUrl() . '/outbox/' . $owner['nickname'] . '?page=' . ($page + 1);
283 $data['partOf'] = DI::baseUrl() . '/outbox/' . $owner['nickname'];
285 $data['orderedItems'] = $list;
292 * Public posts for the given owner
294 * @param array $owner Owner array
295 * @param integer $page Page number
297 * @return array of posts
298 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
299 * @throws \ImagickException
301 public static function getFeatured($owner, $page = null)
303 $condition = ["`uri-id` IN (SELECT `uri-id` FROM `collection-view` WHERE `cid` = ? AND `type` = ?)",
304 Contact::getIdForURL($owner['url'], 0, false), Post\Collection::FEATURED];
306 $condition = DBA::mergeConditions($condition,
307 ['uid' => $owner['uid'],
308 'author-id' => Contact::getIdForURL($owner['url'], 0, false),
309 'private' => [Item::PUBLIC, Item::UNLISTED],
310 'gravity' => [GRAVITY_PARENT, GRAVITY_COMMENT],
311 'network' => Protocol::FEDERATED,
312 'parent-network' => Protocol::FEDERATED,
317 $count = Post::count($condition);
319 $data = ['@context' => ActivityPub::CONTEXT];
320 $data['id'] = DI::baseUrl() . '/featured/' . $owner['nickname'];
321 $data['type'] = 'OrderedCollection';
322 $data['totalItems'] = $count;
325 $data['first'] = DI::baseUrl() . '/featured/' . $owner['nickname'] . '?page=1';
327 $data['type'] = 'OrderedCollectionPage';
330 $items = Post::select(['id'], $condition, ['limit' => [($page - 1) * 20, 20], 'order' => ['created' => true]]);
331 while ($item = Post::fetch($items)) {
332 $activity = self::createActivityFromItem($item['id'], true);
333 $activity['type'] = $activity['type'] == 'Update' ? 'Create' : $activity['type'];
335 // Only list "Create" activity objects here, no reshares
336 if (!empty($activity['object']) && ($activity['type'] == 'Create')) {
337 $list[] = $activity['object'];
343 $data['next'] = DI::baseUrl() . '/featured/' . $owner['nickname'] . '?page=' . ($page + 1);
346 $data['partOf'] = DI::baseUrl() . '/featured/' . $owner['nickname'];
348 $data['orderedItems'] = $list;
355 * Return the service array containing information the used software and it's url
357 * @return array with service data
359 private static function getService()
361 return ['type' => 'Service',
362 'name' => FRIENDICA_PLATFORM . " '" . FRIENDICA_CODENAME . "' " . FRIENDICA_VERSION . '-' . DB_UPDATE_VERSION,
363 'url' => DI::baseUrl()->get()];
367 * Return the ActivityPub profile of the given user
369 * @param int $uid User ID
370 * @return array with profile data
371 * @throws HTTPException\NotFoundException
372 * @throws HTTPException\InternalServerErrorException
374 public static function getProfile(int $uid): array
376 $owner = User::getOwnerDataById($uid);
377 if (!isset($owner['id'])) {
378 DI::logger()->error('Unable to find owner data for uid', ['uid' => $uid, 'callstack' => System::callstack(20)]);
379 throw new HTTPException\NotFoundException('User not found.');
382 $data = ['@context' => ActivityPub::CONTEXT];
383 $data['id'] = $owner['url'];
385 if (!empty($owner['guid'])) {
386 $data['diaspora:guid'] = $owner['guid'];
389 $data['type'] = ActivityPub::ACCOUNT_TYPES[$owner['account-type']];
392 $data['following'] = DI::baseUrl() . '/following/' . $owner['nick'];
393 $data['followers'] = DI::baseUrl() . '/followers/' . $owner['nick'];
394 $data['inbox'] = DI::baseUrl() . '/inbox/' . $owner['nick'];
395 $data['outbox'] = DI::baseUrl() . '/outbox/' . $owner['nick'];
396 $data['featured'] = DI::baseUrl() . '/featured/' . $owner['nick'];
398 $data['inbox'] = DI::baseUrl() . '/friendica/inbox';
401 $data['preferredUsername'] = $owner['nick'];
402 $data['name'] = $owner['name'];
404 if (!empty($owner['country-name'] . $owner['region'] . $owner['locality'])) {
405 $data['vcard:hasAddress'] = ['@type' => 'vcard:Home', 'vcard:country-name' => $owner['country-name'],
406 'vcard:region' => $owner['region'], 'vcard:locality' => $owner['locality']];
409 if (!empty($owner['about'])) {
410 $data['summary'] = BBCode::convertForUriId($owner['uri-id'] ?? 0, $owner['about'], BBCode::EXTERNAL);
413 if (!empty($owner['xmpp']) || !empty($owner['matrix'])) {
414 $data['vcard:hasInstantMessage'] = [];
416 if (!empty($owner['xmpp'])) {
417 $data['vcard:hasInstantMessage'][] = 'xmpp:' . $owner['xmpp'];
419 if (!empty($owner['matrix'])) {
420 $data['vcard:hasInstantMessage'][] = 'matrix:' . $owner['matrix'];
424 $data['url'] = $owner['url'];
425 $data['manuallyApprovesFollowers'] = in_array($owner['page-flags'], [User::PAGE_FLAGS_NORMAL, User::PAGE_FLAGS_PRVGROUP]);
426 $data['discoverable'] = (bool)$owner['net-publish'];
427 $data['publicKey'] = ['id' => $owner['url'] . '#main-key',
428 'owner' => $owner['url'],
429 'publicKeyPem' => $owner['pubkey']];
430 $data['endpoints'] = ['sharedInbox' => DI::baseUrl() . '/inbox'];
431 $data['icon'] = ['type' => 'Image', 'url' => User::getAvatarUrl($owner)];
433 $resourceid = Photo::ridFromURI($owner['photo']);
434 if (!empty($resourceid)) {
435 $photo = Photo::selectFirst(['type'], ["resource-id" => $resourceid]);
436 if (!empty($photo['type'])) {
437 $data['icon']['mediaType'] = $photo['type'];
441 if (!empty($owner['header'])) {
442 $data['image'] = ['type' => 'Image', 'url' => Contact::getHeaderUrlForId($owner['id'], '', $owner['updated'])];
444 $resourceid = Photo::ridFromURI($owner['header']);
445 if (!empty($resourceid)) {
446 $photo = Photo::selectFirst(['type'], ["resource-id" => $resourceid]);
447 if (!empty($photo['type'])) {
448 $data['image']['mediaType'] = $photo['type'];
455 foreach (DI::profileField()->selectByContactId(0, $uid) as $profile_field) {
457 'type' => 'PropertyValue',
458 'name' => $profile_field->label,
459 'value' => BBCode::convertForUriId($owner['uri-id'], $profile_field->value)
463 if (!empty($custom_fields)) {
464 $data['attachment'] = $custom_fields;
467 $data['generator'] = self::getService();
469 // tags: https://kitty.town/@inmysocks/100656097926961126.json
474 * @param string $username
476 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
478 public static function getDeletedUser($username)
481 '@context' => ActivityPub::CONTEXT,
482 'id' => DI::baseUrl() . '/profile/' . $username,
483 'type' => 'Tombstone',
484 'published' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
485 'updated' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
486 'deleted' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
491 * Returns an array with permissions of the thread parent of the given item array
494 * @param bool $is_forum_thread
496 * @return array with permissions
497 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
498 * @throws \ImagickException
500 private static function fetchPermissionBlockFromThreadParent(array $item, bool $is_forum_thread)
502 if (empty($item['thr-parent-id'])) {
506 $parent = Post::selectFirstPost(['author-link'], ['uri-id' => $item['thr-parent-id']]);
507 if (empty($parent)) {
512 'to' => [$parent['author-link']],
518 $parent_profile = APContact::getByURL($parent['author-link']);
520 $item_profile = APContact::getByURL($item['author-link']);
521 $exclude[] = $item['author-link'];
523 if ($item['gravity'] == GRAVITY_PARENT) {
524 $exclude[] = $item['owner-link'];
527 $type = [Tag::TO => 'to', Tag::CC => 'cc', Tag::BTO => 'bto', Tag::BCC => 'bcc'];
528 foreach (Tag::getByURIId($item['thr-parent-id'], [Tag::TO, Tag::CC, Tag::BTO, Tag::BCC]) as $receiver) {
529 if (!empty($parent_profile['followers']) && $receiver['url'] == $parent_profile['followers'] && !empty($item_profile['followers'])) {
530 if (!$is_forum_thread) {
531 $permissions[$type[$receiver['type']]][] = $item_profile['followers'];
533 } elseif (!in_array($receiver['url'], $exclude)) {
534 $permissions[$type[$receiver['type']]][] = $receiver['url'];
542 * Check if the given item id is from ActivityPub
544 * @param integer $item_id
545 * @return boolean "true" if the post is from ActivityPub
547 private static function isAPPost(int $item_id)
549 if (empty($item_id)) {
553 return Post::exists(['id' => $item_id, 'network' => Protocol::ACTIVITYPUB]);
557 * Creates an array of permissions from an item thread
559 * @param array $item Item array
560 * @param boolean $blindcopy addressing via "bcc" or "cc"?
561 * @param integer $last_id Last item id for adding receivers
563 * @return array with permission data
564 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
565 * @throws \ImagickException
567 private static function createPermissionBlockForItem($item, $blindcopy, $last_id = 0)
570 $last_id = $item['id'];
577 // Check if we should always deliver our stuff via BCC
578 if (!empty($item['uid'])) {
579 $owner = User::getOwnerDataById($item['uid']);
580 if (!empty($owner)) {
581 $always_bcc = $owner['hide-friends'];
582 $is_forum = ($owner['account-type'] == User::ACCOUNT_TYPE_COMMUNITY) && $owner['manually-approve'];
584 $profile = APContact::getByURL($owner['url'], false);
585 $follower = $profile['followers'] ?? '';
589 if (DI::config()->get('system', 'ap_always_bcc')) {
593 $parent = Post::selectFirst(['causer-link', 'post-reason'], ['id' => $item['parent']]);
594 if (($parent['post-reason'] == Item::PR_ANNOUNCEMENT) && !empty($parent['causer-link'])) {
595 $profile = APContact::getByURL($parent['causer-link'], false);
596 $is_forum_thread = isset($profile['type']) && $profile['type'] == 'Group';
598 $is_forum_thread = false;
601 if (self::isAnnounce($item) || DI::config()->get('debug', 'total_ap_delivery') || self::isAPPost($last_id)) {
602 // Will be activated in a later step
603 $networks = Protocol::FEDERATED;
605 // For now only send to these contacts:
606 $networks = [Protocol::ACTIVITYPUB, Protocol::OSTATUS];
609 $data = ['to' => [], 'cc' => [], 'bcc' => []];
611 if ($item['gravity'] == GRAVITY_PARENT) {
612 $actor_profile = APContact::getByURL($item['owner-link']);
614 $actor_profile = APContact::getByURL($item['author-link']);
619 $terms = Tag::getByURIId($item['uri-id'], [Tag::MENTION, Tag::IMPLICIT_MENTION, Tag::EXCLUSIVE_MENTION]);
621 if ($item['private'] != Item::PRIVATE) {
622 // Directly mention the original author upon a quoted reshare.
623 // Else just ensure that the original author receives the reshare.
624 $announce = self::getAnnounceArray($item);
625 if (!empty($announce['comment'])) {
626 $data['to'][] = $announce['actor']['url'];
627 } elseif (!empty($announce)) {
628 $data['cc'][] = $announce['actor']['url'];
631 $data = array_merge($data, self::fetchPermissionBlockFromThreadParent($item, $is_forum_thread));
633 // Check if the item is completely public or unlisted
634 if ($item['private'] == Item::PUBLIC) {
635 $data['to'][] = ActivityPub::PUBLIC_COLLECTION;
637 $data['cc'][] = ActivityPub::PUBLIC_COLLECTION;
640 foreach ($terms as $term) {
641 $profile = APContact::getByURL($term['url'], false);
642 if (!empty($profile)) {
643 if ($term['type'] == Tag::EXCLUSIVE_MENTION) {
645 if (!empty($profile['followers']) && ($profile['type'] == 'Group')) {
646 $data['cc'][] = $profile['followers'];
649 $data['to'][] = $profile['url'];
653 $receiver_list = Item::enumeratePermissions($item, true);
655 foreach ($terms as $term) {
656 $cid = Contact::getIdForURL($term['url'], $item['uid']);
657 if (!empty($cid) && in_array($cid, $receiver_list)) {
658 $contact = DBA::selectFirst('contact', ['url', 'network', 'protocol', 'gsid'], ['id' => $cid, 'network' => Protocol::FEDERATED]);
659 if (!DBA::isResult($contact) || !self::isAPContact($contact, $networks)) {
663 $profile = APContact::getByURL($term['url'], false);
664 if (!empty($profile)) {
665 if ($term['type'] == Tag::EXCLUSIVE_MENTION) {
667 if (!empty($profile['followers']) && ($profile['type'] == 'Group')) {
668 $data['cc'][] = $profile['followers'];
671 $data['to'][] = $profile['url'];
676 if ($is_forum && !$exclusive && !empty($follower)) {
677 $data['cc'][] = $follower;
678 } elseif (!$exclusive) {
679 foreach ($receiver_list as $receiver) {
680 $contact = DBA::selectFirst('contact', ['url', 'hidden', 'network', 'protocol', 'gsid'], ['id' => $receiver, 'network' => Protocol::FEDERATED]);
681 if (!DBA::isResult($contact) || !self::isAPContact($contact, $networks)) {
685 if (!empty($profile = APContact::getByURL($contact['url'], false))) {
686 if ($contact['hidden'] || $always_bcc) {
687 $data['bcc'][] = $profile['url'];
689 $data['cc'][] = $profile['url'];
696 if (!empty($item['parent'])) {
697 $parents = Post::select(['id', 'author-link', 'owner-link', 'gravity', 'uri'], ['parent' => $item['parent']], ['order' => ['id']]);
698 while ($parent = Post::fetch($parents)) {
699 if ($parent['gravity'] == GRAVITY_PARENT) {
700 $profile = APContact::getByURL($parent['owner-link'], false);
701 if (!empty($profile)) {
702 if ($item['gravity'] != GRAVITY_PARENT) {
703 // Comments to forums are directed to the forum
704 // But comments to forums aren't directed to the followers collection
705 // This rule is only valid when the actor isn't the forum.
706 // The forum needs to transmit their content to their followers.
707 if (($profile['type'] == 'Group') && ($profile['url'] != ($actor_profile['url'] ?? ''))) {
708 $data['to'][] = $profile['url'];
710 $data['cc'][] = $profile['url'];
711 if (($item['private'] != Item::PRIVATE) && !empty($actor_profile['followers'])&& !$is_forum_thread) {
712 $data['cc'][] = $actor_profile['followers'];
715 } elseif (!$exclusive && !$is_forum_thread) {
716 // Public thread parent post always are directed to the followers.
717 if ($item['private'] != Item::PRIVATE) {
718 $data['cc'][] = $actor_profile['followers'];
724 // Don't include data from future posts
725 if ($parent['id'] >= $last_id) {
729 $profile = APContact::getByURL($parent['author-link'], false);
730 if (!empty($profile)) {
731 if (($profile['type'] == 'Group') || ($parent['uri'] == $item['thr-parent'])) {
732 $data['to'][] = $profile['url'];
734 $data['cc'][] = $profile['url'];
738 DBA::close($parents);
741 $data['to'] = array_unique($data['to']);
742 $data['cc'] = array_unique($data['cc']);
743 $data['bcc'] = array_unique($data['bcc']);
745 if (($key = array_search($item['author-link'], $data['to'])) !== false) {
746 unset($data['to'][$key]);
749 if (($key = array_search($item['author-link'], $data['cc'])) !== false) {
750 unset($data['cc'][$key]);
753 if (($key = array_search($item['author-link'], $data['bcc'])) !== false) {
754 unset($data['bcc'][$key]);
757 foreach ($data['to'] as $to) {
758 if (($key = array_search($to, $data['cc'])) !== false) {
759 unset($data['cc'][$key]);
762 if (($key = array_search($to, $data['bcc'])) !== false) {
763 unset($data['bcc'][$key]);
767 foreach ($data['cc'] as $cc) {
768 if (($key = array_search($cc, $data['bcc'])) !== false) {
769 unset($data['bcc'][$key]);
773 $receivers = ['to' => array_values($data['to']), 'cc' => array_values($data['cc']), 'bcc' => array_values($data['bcc'])];
776 unset($receivers['bcc']);
779 foreach (['to' => Tag::TO, 'cc' => Tag::CC, 'bcc' => Tag::BCC] as $element => $type) {
780 if (!empty($receivers[$element])) {
781 foreach ($receivers[$element] as $receiver) {
782 if ($receiver == ActivityPub::PUBLIC_COLLECTION) {
783 $name = Receiver::PUBLIC_COLLECTION;
785 $name = trim(parse_url($receiver, PHP_URL_PATH), '/');
787 Tag::store($item['uri-id'], $type, $name, $receiver);
796 * Check if an inbox is archived
798 * @param string $url Inbox url
800 * @return boolean "true" if inbox is archived
802 public static function archivedInbox($url)
804 return DBA::exists('inbox-status', ['url' => $url, 'archive' => true]);
808 * Check if a given contact should be delivered via AP
810 * @param array $contact
811 * @param array $networks
815 private static function isAPContact(array $contact, array $networks)
817 if (in_array($contact['network'], $networks) || ($contact['protocol'] == Protocol::ACTIVITYPUB)) {
821 return GServer::getProtocol($contact['gsid'] ?? 0) == Post\DeliveryData::ACTIVITYPUB;
825 * Fetches a list of inboxes of followers of a given user
827 * @param integer $uid User ID
828 * @param boolean $personal fetch personal inboxes
829 * @param boolean $all_ap Retrieve all AP enabled inboxes
831 * @return array of follower inboxes
832 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
833 * @throws \ImagickException
835 public static function fetchTargetInboxesforUser($uid, $personal = false, bool $all_ap = false)
841 if (!empty($item['uid'])) {
842 $profile = User::getOwnerDataById($item['uid']);
843 if (!empty($profile)) {
844 $isforum = $profile['account-type'] == User::ACCOUNT_TYPE_COMMUNITY;
848 if (DI::config()->get('debug', 'total_ap_delivery') || $all_ap) {
849 // Will be activated in a later step
850 $networks = Protocol::FEDERATED;
852 // For now only send to these contacts:
853 $networks = [Protocol::ACTIVITYPUB, Protocol::OSTATUS];
856 $condition = ['uid' => $uid, 'archive' => false, 'pending' => false, 'blocked' => false, 'network' => Protocol::FEDERATED];
859 $condition['rel'] = [Contact::FOLLOWER, Contact::FRIEND];
862 $contacts = DBA::select('contact', ['id', 'url', 'network', 'protocol', 'gsid'], $condition);
863 while ($contact = DBA::fetch($contacts)) {
864 if (!self::isAPContact($contact, $networks)) {
868 if ($isforum && ($contact['network'] == Protocol::DFRN)) {
872 if (Network::isUrlBlocked($contact['url'])) {
876 $profile = APContact::getByURL($contact['url'], false);
877 if (!empty($profile)) {
878 if (empty($profile['sharedinbox']) || $personal || Contact::isLocal($contact['url'])) {
879 $target = $profile['inbox'];
881 $target = $profile['sharedinbox'];
883 if (!self::archivedInbox($target)) {
884 $inboxes[$target][] = $contact['id'];
888 DBA::close($contacts);
894 * Fetches an array of inboxes for the given item and user
896 * @param array $item Item array
897 * @param integer $uid User ID
898 * @param boolean $personal fetch personal inboxes
899 * @param integer $last_id Last item id for adding receivers
900 * @return array with inboxes
901 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
902 * @throws \ImagickException
904 public static function fetchTargetInboxes($item, $uid, $personal = false, $last_id = 0)
906 $permissions = self::createPermissionBlockForItem($item, true, $last_id);
907 if (empty($permissions)) {
913 if ($item['gravity'] == GRAVITY_ACTIVITY) {
914 $item_profile = APContact::getByURL($item['author-link'], false);
916 $item_profile = APContact::getByURL($item['owner-link'], false);
919 if (empty($item_profile)) {
923 $profile_uid = User::getIdForURL($item_profile['url']);
925 foreach (['to', 'cc', 'bto', 'bcc'] as $element) {
926 if (empty($permissions[$element])) {
930 $blindcopy = in_array($element, ['bto', 'bcc']);
932 foreach ($permissions[$element] as $receiver) {
933 if (empty($receiver) || Network::isUrlBlocked($receiver)) {
937 if ($item_profile && ($receiver == $item_profile['followers']) && ($uid == $profile_uid)) {
938 $inboxes = array_merge($inboxes, self::fetchTargetInboxesforUser($uid, $personal, self::isAPPost($last_id)));
940 $profile = APContact::getByURL($receiver, false);
941 if (!empty($profile)) {
942 $contact = Contact::getByURLForUser($receiver, $uid, false, ['id']);
944 if (empty($profile['sharedinbox']) || $personal || $blindcopy || Contact::isLocal($receiver)) {
945 $target = $profile['inbox'];
947 $target = $profile['sharedinbox'];
949 if (!self::archivedInbox($target)) {
950 $inboxes[$target][] = $contact['id'] ?? 0;
961 * Creates an array in the structure of the item table for a given mail id
963 * @param integer $mail_id
968 public static function ItemArrayFromMail($mail_id, $use_title = false)
970 $mail = DBA::selectFirst('mail', [], ['id' => $mail_id]);
971 if (!DBA::isResult($mail)) {
975 $reply = DBA::selectFirst('mail', ['uri', 'uri-id', 'from-url'], ['parent-uri' => $mail['parent-uri'], 'reply' => false]);
976 if (!DBA::isResult($reply)) {
980 // Making the post more compatible for Mastodon by:
981 // - Making it a note and not an article (no title)
982 // - Moving the title into the "summary" field that is used as a "content warning"
985 $mail['body'] = '[abstract]' . $mail['title'] . "[/abstract]\n" . $mail['body'];
989 $mail['content-warning'] = '';
990 $mail['author-link'] = $mail['owner-link'] = $mail['from-url'];
991 $mail['owner-id'] = $mail['author-id'];
992 $mail['allow_cid'] = '<'.$mail['contact-id'].'>';
993 $mail['allow_gid'] = '';
994 $mail['deny_cid'] = '';
995 $mail['deny_gid'] = '';
996 $mail['private'] = Item::PRIVATE;
997 $mail['deleted'] = false;
998 $mail['edited'] = $mail['created'];
999 $mail['plink'] = DI::baseUrl() . '/message/' . $mail['id'];
1000 $mail['parent-uri'] = $reply['uri'];
1001 $mail['parent-uri-id'] = $reply['uri-id'];
1002 $mail['parent-author-id'] = Contact::getIdForURL($reply['from-url'], 0, false);
1003 $mail['gravity'] = ($mail['reply'] ? GRAVITY_COMMENT: GRAVITY_PARENT);
1004 $mail['event-type'] = '';
1005 $mail['language'] = '';
1006 $mail['parent'] = 0;
1012 * Creates an activity array for a given mail id
1014 * @param integer $mail_id
1015 * @param boolean $object_mode Is the activity item is used inside another object?
1017 * @return array of activity
1018 * @throws \Exception
1020 public static function createActivityFromMail($mail_id, $object_mode = false)
1022 $mail = self::ItemArrayFromMail($mail_id);
1026 $object = self::createNote($mail);
1028 if (!$object_mode) {
1029 $data = ['@context' => ActivityPub::CONTEXT];
1034 $data['id'] = $mail['uri'] . '/Create';
1035 $data['type'] = 'Create';
1036 $data['actor'] = $mail['author-link'];
1037 $data['published'] = DateTimeFormat::utc($mail['created'] . '+00:00', DateTimeFormat::ATOM);
1038 $data['instrument'] = self::getService();
1039 $data = array_merge($data, self::createPermissionBlockForItem($mail, true));
1041 if (empty($data['to']) && !empty($data['cc'])) {
1042 $data['to'] = $data['cc'];
1045 if (empty($data['to']) && !empty($data['bcc'])) {
1046 $data['to'] = $data['bcc'];
1050 unset($data['bcc']);
1052 $object['to'] = $data['to'];
1053 $object['tag'] = [['type' => 'Mention', 'href' => $object['to'][0], 'name' => '']];
1055 unset($object['cc']);
1056 unset($object['bcc']);
1058 $data['directMessage'] = true;
1060 $data['object'] = $object;
1062 $owner = User::getOwnerDataById($mail['uid']);
1064 if (!$object_mode && !empty($owner)) {
1065 return LDSignature::sign($data, $owner);
1072 * Returns the activity type of a given item
1074 * @param array $item
1076 * @return string with activity type
1077 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1078 * @throws \ImagickException
1080 private static function getTypeOfItem($item)
1084 // Only check for a reshare, if it is a real reshare and no quoted reshare
1085 if (strpos($item['body'], "[share") === 0) {
1086 $announce = self::getAnnounceArray($item);
1087 $reshared = !empty($announce);
1092 } elseif ($item['verb'] == Activity::POST) {
1093 if ($item['created'] == $item['edited']) {
1098 } elseif ($item['verb'] == Activity::LIKE) {
1100 } elseif ($item['verb'] == Activity::DISLIKE) {
1102 } elseif ($item['verb'] == Activity::ATTEND) {
1104 } elseif ($item['verb'] == Activity::ATTENDNO) {
1106 } elseif ($item['verb'] == Activity::ATTENDMAYBE) {
1107 $type = 'TentativeAccept';
1108 } elseif ($item['verb'] == Activity::FOLLOW) {
1110 } elseif ($item['verb'] == Activity::TAG) {
1112 } elseif ($item['verb'] == Activity::ANNOUNCE) {
1122 * Creates the activity or fetches it from the cache
1124 * @param integer $item_id
1125 * @param boolean $force Force new cache entry
1127 * @return array with the activity
1128 * @throws \Exception
1130 public static function createCachedActivityFromItem($item_id, $force = false)
1132 $cachekey = 'APDelivery:createActivity:' . $item_id;
1135 $data = DI::cache()->get($cachekey);
1136 if (!is_null($data)) {
1141 $data = self::createActivityFromItem($item_id);
1143 DI::cache()->set($cachekey, $data, Duration::QUARTER_HOUR);
1148 * Creates an activity array for a given item id
1150 * @param integer $item_id
1151 * @param boolean $object_mode Is the activity item is used inside another object?
1153 * @return false|array
1154 * @throws \Exception
1156 public static function createActivityFromItem(int $item_id, bool $object_mode = false)
1158 Logger::info('Fetching activity', ['item' => $item_id]);
1159 $item = Post::selectFirst(Item::DELIVER_FIELDLIST, ['id' => $item_id, 'parent-network' => Protocol::NATIVE_SUPPORT]);
1160 if (!DBA::isResult($item)) {
1164 if (empty($item['uri-id'])) {
1165 Logger::warning('Item without uri-id', ['item' => $item]);
1169 if (!$item['deleted']) {
1170 $condition = ['item-uri' => $item['uri'], 'protocol' => Conversation::PARCEL_ACTIVITYPUB];
1171 $conversation = DBA::selectFirst('conversation', ['source'], $condition);
1172 if (!$item['origin'] && DBA::isResult($conversation)) {
1173 $data = json_decode($conversation['source'], true);
1174 if (!empty($data['type'])) {
1175 if (in_array($data['type'], ['Create', 'Update'])) {
1177 unset($data['@context']);
1178 unset($data['signature']);
1180 Logger::info('Return stored conversation', ['item' => $item_id]);
1182 } elseif (in_array('as:' . $data['type'], Receiver::CONTENT_TYPES)) {
1183 if (!empty($data['@context'])) {
1184 $context = $data['@context'];
1185 unset($data['@context']);
1187 unset($data['actor']);
1194 $type = self::getTypeOfItem($item);
1196 if (!$object_mode) {
1197 $data = ['@context' => $context ?? ActivityPub::CONTEXT];
1199 if ($item['deleted'] && ($item['gravity'] == GRAVITY_ACTIVITY)) {
1201 } elseif ($item['deleted']) {
1208 if ($type == 'Delete') {
1209 $data['id'] = Item::newURI($item['uid'], $item['guid']) . '/' . $type;;
1210 } elseif (($item['gravity'] == GRAVITY_ACTIVITY) && ($type != 'Undo')) {
1211 $data['id'] = $item['uri'];
1213 $data['id'] = $item['uri'] . '/' . $type;
1216 $data['type'] = $type;
1218 if (($type != 'Announce') || ($item['gravity'] != GRAVITY_PARENT)) {
1219 $data['actor'] = $item['author-link'];
1221 $data['actor'] = $item['owner-link'];
1224 $data['published'] = DateTimeFormat::utc($item['created'] . '+00:00', DateTimeFormat::ATOM);
1226 $data['instrument'] = self::getService();
1228 $data = array_merge($data, self::createPermissionBlockForItem($item, false));
1230 if (in_array($data['type'], ['Create', 'Update', 'Delete'])) {
1231 $data['object'] = $object ?? self::createNote($item);
1232 $data['published'] = DateTimeFormat::utcNow(DateTimeFormat::ATOM);
1233 } elseif ($data['type'] == 'Add') {
1234 $data = self::createAddTag($item, $data);
1235 } elseif ($data['type'] == 'Announce') {
1236 if ($item['verb'] == ACTIVITY::ANNOUNCE) {
1237 $data['object'] = $item['thr-parent'];
1239 $data = self::createAnnounce($item, $data);
1241 } elseif ($data['type'] == 'Follow') {
1242 $data['object'] = $item['parent-uri'];
1243 } elseif ($data['type'] == 'Undo') {
1244 $data['object'] = self::createActivityFromItem($item_id, true);
1246 $data['diaspora:guid'] = $item['guid'];
1247 if (!empty($item['signed_text'])) {
1248 $data['diaspora:like'] = $item['signed_text'];
1250 $data['object'] = $item['thr-parent'];
1253 if (!empty($item['contact-uid'])) {
1254 $uid = $item['contact-uid'];
1256 $uid = $item['uid'];
1259 $owner = User::getOwnerDataById($uid);
1261 Logger::info('Fetched activity', ['item' => $item_id, 'uid' => $uid]);
1263 // We don't sign if we aren't the actor. This is important for relaying content especially for forums
1264 if (!$object_mode && !empty($owner) && ($data['actor'] == $owner['url'])) {
1265 return LDSignature::sign($data, $owner);
1270 /// @todo Create "conversation" entry
1274 * Creates a location entry for a given item array
1276 * @param array $item
1278 * @return array with location array
1280 private static function createLocation($item)
1282 $location = ['type' => 'Place'];
1284 if (!empty($item['location'])) {
1285 $location['name'] = $item['location'];
1290 if (empty($item['coord'])) {
1291 $coord = Map::getCoordinates($item['location']);
1293 $coords = explode(' ', $item['coord']);
1294 if (count($coords) == 2) {
1295 $coord = ['lat' => $coords[0], 'lon' => $coords[1]];
1299 if (!empty($coord['lat']) && !empty($coord['lon'])) {
1300 $location['latitude'] = $coord['lat'];
1301 $location['longitude'] = $coord['lon'];
1308 * Returns a tag array for a given item array
1310 * @param array $item
1312 * @return array of tags
1313 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1315 private static function createTagList($item)
1319 $terms = Tag::getByURIId($item['uri-id'], [Tag::HASHTAG, Tag::MENTION, Tag::IMPLICIT_MENTION, Tag::EXCLUSIVE_MENTION]);
1320 foreach ($terms as $term) {
1321 if ($term['type'] == Tag::HASHTAG) {
1322 $url = DI::baseUrl() . '/search?tag=' . urlencode($term['name']);
1323 $tags[] = ['type' => 'Hashtag', 'href' => $url, 'name' => '#' . $term['name']];
1325 $contact = Contact::getByURL($term['url'], false, ['addr']);
1326 if (empty($contact)) {
1329 if (!empty($contact['addr'])) {
1330 $mention = '@' . $contact['addr'];
1332 $mention = '@' . $term['url'];
1335 $tags[] = ['type' => 'Mention', 'href' => $term['url'], 'name' => $mention];
1339 $announce = self::getAnnounceArray($item);
1340 // Mention the original author upon commented reshares
1341 if (!empty($announce['comment'])) {
1342 $tags[] = ['type' => 'Mention', 'href' => $announce['actor']['url'], 'name' => '@' . $announce['actor']['addr']];
1349 * Adds attachment data to the JSON document
1351 * @param array $item Data of the item that is to be posted
1352 * @param string $type Object type
1354 * @return array with attachment data
1355 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1357 private static function createAttachmentList($item, $type)
1361 $uriids = [$item['uri-id']];
1362 $shared = BBCode::fetchShareAttributes($item['body']);
1363 if (!empty($shared['guid'])) {
1364 $shared_item = Post::selectFirst(['uri-id'], ['guid' => $shared['guid']]);
1365 if (!empty($shared_item['uri-id'])) {
1366 $uriids[] = $shared_item['uri-id'];
1371 foreach ($uriids as $uriid) {
1372 foreach (Post\Media::getByURIId($uriid, [Post\Media::AUDIO, Post\Media::IMAGE, Post\Media::VIDEO, Post\Media::DOCUMENT, Post\Media::TORRENT]) as $attachment) {
1373 if (in_array($attachment['url'], $urls)) {
1376 $urls[] = $attachment['url'];
1378 $attach = ['type' => 'Document',
1379 'mediaType' => $attachment['mimetype'],
1380 'url' => $attachment['url'],
1381 'name' => $attachment['description']];
1383 if (!empty($attachment['height'])) {
1384 $attach['height'] = $attachment['height'];
1387 if (!empty($attachment['width'])) {
1388 $attach['width'] = $attachment['width'];
1391 if (!empty($attachment['preview'])) {
1392 $attach['image'] = $attachment['preview'];
1395 $attachments[] = $attach;
1399 return $attachments;
1403 * Callback function to replace a Friendica style mention in a mention for a summary
1405 * @param array $match Matching values for the callback
1406 * @return string Replaced mention
1407 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1409 private static function mentionAddrCallback($match)
1411 if (empty($match[1])) {
1415 $data = Contact::getByURL($match[1], false, ['addr']);
1416 if (empty($data['addr'])) {
1420 return '@' . $data['addr'];
1424 * Remove image elements since they are added as attachment
1426 * @param string $body
1428 * @return string with removed images
1430 private static function removePictures($body)
1432 // Simplify image codes
1433 $body = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '[img]$3[/img]', $body);
1434 $body = preg_replace("/\[img\=(.*?)\](.*?)\[\/img\]/ism", '[img]$1[/img]', $body);
1436 // Now remove local links
1437 $body = preg_replace_callback(
1438 '/\[url=([^\[\]]*)\]\[img\](.*)\[\/img\]\[\/url\]/Usi',
1440 // We remove the link when it is a link to a local photo page
1441 if (Photo::isLocalPage($match[1])) {
1444 // otherwise we just return the link
1445 return '[url]' . $match[1] . '[/url]';
1450 // Remove all pictures
1451 $body = preg_replace("/\[img\]([^\[\]]*)\[\/img\]/Usi", '', $body);
1457 * Fetches the "context" value for a givem item array from the "conversation" table
1459 * @param array $item
1461 * @return string with context url
1462 * @throws \Exception
1464 private static function fetchContextURLForItem($item)
1466 $conversation = DBA::selectFirst('conversation', ['conversation-href', 'conversation-uri'], ['item-uri' => $item['parent-uri']]);
1467 if (DBA::isResult($conversation) && !empty($conversation['conversation-href'])) {
1468 $context_uri = $conversation['conversation-href'];
1469 } elseif (DBA::isResult($conversation) && !empty($conversation['conversation-uri'])) {
1470 $context_uri = $conversation['conversation-uri'];
1472 $context_uri = $item['parent-uri'] . '#context';
1474 return $context_uri;
1478 * Returns if the post contains sensitive content ("nsfw")
1480 * @param integer $uri_id
1483 * @throws \Exception
1485 private static function isSensitive($uri_id)
1487 return DBA::exists('tag-view', ['uri-id' => $uri_id, 'name' => 'nsfw', 'type' => Tag::HASHTAG]);
1491 * Creates event data
1493 * @param array $item
1495 * @return array with the event data
1496 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1498 private static function createEvent($item)
1501 $event['name'] = $item['event-summary'];
1502 $event['content'] = BBCode::convertForUriId($item['uri-id'], $item['event-desc'], BBCode::ACTIVITYPUB);
1503 $event['startTime'] = DateTimeFormat::utc($item['event-start'], 'c');
1505 if (!$item['event-nofinish']) {
1506 $event['endTime'] = DateTimeFormat::utc($item['event-finish'], 'c');
1509 if (!empty($item['event-location'])) {
1510 $item['location'] = $item['event-location'];
1511 $event['location'] = self::createLocation($item);
1514 // 2021.12: Backward compatibility value, all the events now "adjust" to the viewer timezone
1515 $event['dfrn:adjust'] = true;
1521 * Creates a note/article object array
1523 * @param array $item
1525 * @return array with the object data
1526 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1527 * @throws \ImagickException
1529 public static function createNote($item)
1535 // We are treating posts differently when they are directed to a community.
1536 // This is done to better support Lemmy. Most of the changes should work with other systems as well.
1537 // But to not risk compatibility issues we currently perform the changes only for communities.
1538 if ($item['gravity'] == GRAVITY_PARENT) {
1539 $isCommunityPost = !empty(Tag::getByURIId($item['uri-id'], [Tag::EXCLUSIVE_MENTION]));
1540 $links = Post\Media::getByURIId($item['uri-id'], [Post\Media::HTML]);
1541 if ($isCommunityPost && (count($links) == 1)) {
1542 $link = $links[0]['url'];
1545 $isCommunityPost = false;
1548 if ($item['event-type'] == 'event') {
1550 } elseif (!empty($item['title'])) {
1551 if (!$isCommunityPost || empty($link)) {
1554 // "Page" is used by Lemmy for posts that contain an external link
1561 if ($item['deleted']) {
1562 $type = 'Tombstone';
1566 $data['id'] = $item['uri'];
1567 $data['type'] = $type;
1569 if ($item['deleted']) {
1573 $data['summary'] = BBCode::toPlaintext(BBCode::getAbstract($item['body'], Protocol::ACTIVITYPUB));
1575 if ($item['uri'] != $item['thr-parent']) {
1576 $data['inReplyTo'] = $item['thr-parent'];
1578 $data['inReplyTo'] = null;
1581 $data['diaspora:guid'] = $item['guid'];
1582 $data['published'] = DateTimeFormat::utc($item['created'] . '+00:00', DateTimeFormat::ATOM);
1584 if ($item['created'] != $item['edited']) {
1585 $data['updated'] = DateTimeFormat::utc($item['edited'] . '+00:00', DateTimeFormat::ATOM);
1588 $data['url'] = $link ?? $item['plink'];
1589 $data['attributedTo'] = $item['author-link'];
1590 $data['sensitive'] = self::isSensitive($item['uri-id']);
1591 $data['context'] = self::fetchContextURLForItem($item);
1593 if (!empty($item['title'])) {
1594 $data['name'] = BBCode::toPlaintext($item['title'], false);
1597 $permission_block = self::createPermissionBlockForItem($item, false);
1599 $body = $item['body'];
1601 if ($type == 'Note') {
1602 $body = $item['raw-body'] ?? self::removePictures($body);
1606 * @todo Improve the automated summary
1607 * This part is currently deactivated. The automated summary seems to be more
1608 * confusing than helping. But possibly we will find a better way.
1609 * So the code is left here for now as a reminder
1611 * } elseif (($type == 'Article') && empty($data['summary'])) {
1612 * $regexp = "/[@!]\[url\=([^\[\]]*)\].*?\[\/url\]/ism";
1613 * $summary = preg_replace_callback($regexp, ['self', 'mentionAddrCallback'], $body);
1614 * $data['summary'] = BBCode::toPlaintext(Plaintext::shorten(self::removePictures($summary), 1000));
1618 if (empty($item['uid']) || !Feature::isEnabled($item['uid'], 'explicit_mentions')) {
1619 $body = self::prependMentions($body, $item['uri-id'], $item['author-link']);
1622 if ($type == 'Event') {
1623 $data = array_merge($data, self::createEvent($item));
1625 if ($isCommunityPost) {
1626 // For community posts we remove the visible "!user@domain.tld".
1627 // This improves the look at systems like Lemmy.
1628 // Also in the future we should control the community delivery via other methods.
1629 $body = preg_replace("/!\[url\=[^\[\]]*\][^\[\]]*\[\/url\]/ism", '', $body);
1632 if ($type == 'Page') {
1633 // When we transmit "Page" posts we have to remove the attachment.
1634 // The attachment contains the link that we already transmit in the "url" field.
1635 $body = preg_replace("/\s*\[attachment .*?\].*?\[\/attachment\]\s*/ism", '', $body);
1638 $body = BBCode::setMentionsToNicknames($body);
1640 $data['content'] = BBCode::convertForUriId($item['uri-id'], $body, BBCode::ACTIVITYPUB);
1643 // The regular "content" field does contain a minimized HTML. This is done since systems like
1644 // Mastodon has got problems with - for example - embedded pictures.
1645 // The contentMap does contain the unmodified HTML.
1646 $language = self::getLanguage($item);
1647 if (!empty($language)) {
1648 $richbody = BBCode::setMentionsToNicknames($item['body'] ?? '');
1649 $richbody = BBCode::removeAttachment($richbody);
1651 $data['contentMap'][$language] = BBCode::convertForUriId($item['uri-id'], $richbody, BBCode::EXTERNAL);
1654 $data['source'] = ['content' => $item['body'], 'mediaType' => "text/bbcode"];
1656 if (!empty($item['signed_text']) && ($item['uri'] != $item['thr-parent'])) {
1657 $data['diaspora:comment'] = $item['signed_text'];
1660 $data['attachment'] = self::createAttachmentList($item, $type);
1661 $data['tag'] = self::createTagList($item);
1663 if (empty($data['location']) && (!empty($item['coord']) || !empty($item['location']))) {
1664 $data['location'] = self::createLocation($item);
1667 if (!empty($item['app'])) {
1668 $data['generator'] = ['type' => 'Application', 'name' => $item['app']];
1671 $data = array_merge($data, $permission_block);
1677 * Fetches the language from the post, the user or the system.
1679 * @param array $item
1681 * @return string language string
1683 private static function getLanguage(array $item)
1685 // Try to fetch the language from the post itself
1686 if (!empty($item['language'])) {
1687 $languages = array_keys(json_decode($item['language'], true));
1688 if (!empty($languages[0])) {
1689 return $languages[0];
1693 // Otherwise use the user's language
1694 if (!empty($item['uid'])) {
1695 $user = DBA::selectFirst('user', ['language'], ['uid' => $item['uid']]);
1696 if (!empty($user['language'])) {
1697 return $user['language'];
1701 // And finally just use the system language
1702 return DI::config()->get('system', 'language');
1706 * Creates an an "add tag" entry
1708 * @param array $item
1709 * @param array $data activity data
1711 * @return array with activity data for adding tags
1712 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1713 * @throws \ImagickException
1715 private static function createAddTag($item, $data)
1717 $object = XML::parseString($item['object']);
1718 $target = XML::parseString($item["target"]);
1720 $data['diaspora:guid'] = $item['guid'];
1721 $data['actor'] = $item['author-link'];
1722 $data['target'] = (string)$target->id;
1723 $data['summary'] = BBCode::toPlaintext($item['body']);
1724 $data['object'] = ['id' => (string)$object->id, 'type' => 'tag', 'name' => (string)$object->title, 'content' => (string)$object->content];
1730 * Creates an announce object entry
1732 * @param array $item
1733 * @param array $data activity data
1735 * @return array with activity data
1736 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1737 * @throws \ImagickException
1739 private static function createAnnounce($item, $data)
1741 $orig_body = $item['body'];
1742 $announce = self::getAnnounceArray($item);
1743 if (empty($announce)) {
1744 $data['type'] = 'Create';
1745 $data['object'] = self::createNote($item);
1749 if (empty($announce['comment'])) {
1750 // Pure announce, without a quote
1751 $data['type'] = 'Announce';
1752 $data['object'] = $announce['object']['uri'];
1757 $data['type'] = 'Create';
1758 $item['body'] = $announce['comment'] . "\n" . $announce['object']['plink'];
1759 $data['object'] = self::createNote($item);
1761 /// @todo Finally descide how to implement this in AP. This is a possible way:
1762 $data['object']['attachment'][] = self::createNote($announce['object']);
1764 $data['object']['source']['content'] = $orig_body;
1769 * Return announce related data if the item is an annunce
1771 * @param array $item
1775 public static function getAnnounceArray($item)
1777 $reshared = Item::getShareArray($item);
1778 if (empty($reshared['guid'])) {
1782 $reshared_item = Post::selectFirst(Item::DELIVER_FIELDLIST, ['guid' => $reshared['guid']]);
1783 if (!DBA::isResult($reshared_item)) {
1787 if (!in_array($reshared_item['network'], [Protocol::ACTIVITYPUB, Protocol::DFRN])) {
1791 $profile = APContact::getByURL($reshared_item['author-link'], false);
1792 if (empty($profile)) {
1796 return ['object' => $reshared_item, 'actor' => $profile, 'comment' => $reshared['comment']];
1800 * Checks if the provided item array is an announce
1802 * @param array $item
1806 public static function isAnnounce($item)
1808 if (!empty($item['verb']) && ($item['verb'] == Activity::ANNOUNCE)) {
1812 $announce = self::getAnnounceArray($item);
1813 if (empty($announce)) {
1817 return empty($announce['comment']);
1821 * Creates an activity id for a given contact id
1823 * @param integer $cid Contact ID of target
1825 * @return bool|string activity id
1827 public static function activityIDFromContact($cid)
1829 $contact = DBA::selectFirst('contact', ['uid', 'id', 'created'], ['id' => $cid]);
1830 if (!DBA::isResult($contact)) {
1834 $hash = hash('ripemd128', $contact['uid'].'-'.$contact['id'].'-'.$contact['created']);
1835 $uuid = substr($hash, 0, 8). '-' . substr($hash, 8, 4) . '-' . substr($hash, 12, 4) . '-' . substr($hash, 16, 4) . '-' . substr($hash, 20, 12);
1836 return DI::baseUrl() . '/activity/' . $uuid;
1840 * Transmits a contact suggestion to a given inbox
1842 * @param integer $uid User ID
1843 * @param string $inbox Target inbox
1844 * @param integer $suggestion_id Suggestion ID
1846 * @return boolean was the transmission successful?
1847 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1849 public static function sendContactSuggestion($uid, $inbox, $suggestion_id)
1851 $owner = User::getOwnerDataById($uid);
1853 $suggestion = DI::fsuggest()->selectOneById($suggestion_id);
1855 $data = ['@context' => ActivityPub::CONTEXT,
1856 'id' => DI::baseUrl() . '/activity/' . System::createGUID(),
1857 'type' => 'Announce',
1858 'actor' => $owner['url'],
1859 'object' => $suggestion->url,
1860 'content' => $suggestion->note,
1861 'instrument' => self::getService(),
1862 'to' => [ActivityPub::PUBLIC_COLLECTION],
1865 $signed = LDSignature::sign($data, $owner);
1867 Logger::info('Deliver profile deletion for user ' . $uid . ' to ' . $inbox . ' via ActivityPub');
1868 return HTTPSignature::transmit($signed, $inbox, $uid);
1872 * Transmits a profile relocation to a given inbox
1874 * @param integer $uid User ID
1875 * @param string $inbox Target inbox
1877 * @return boolean was the transmission successful?
1878 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1880 public static function sendProfileRelocation($uid, $inbox)
1882 $owner = User::getOwnerDataById($uid);
1884 $data = ['@context' => ActivityPub::CONTEXT,
1885 'id' => DI::baseUrl() . '/activity/' . System::createGUID(),
1886 'type' => 'dfrn:relocate',
1887 'actor' => $owner['url'],
1888 'object' => $owner['url'],
1889 'published' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
1890 'instrument' => self::getService(),
1891 'to' => [ActivityPub::PUBLIC_COLLECTION],
1894 $signed = LDSignature::sign($data, $owner);
1896 Logger::info('Deliver profile relocation for user ' . $uid . ' to ' . $inbox . ' via ActivityPub');
1897 return HTTPSignature::transmit($signed, $inbox, $uid);
1901 * Transmits a profile deletion to a given inbox
1903 * @param integer $uid User ID
1904 * @param string $inbox Target inbox
1906 * @return boolean was the transmission successful?
1907 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1909 public static function sendProfileDeletion($uid, $inbox)
1911 $owner = User::getOwnerDataById($uid);
1913 if (empty($owner)) {
1914 Logger::error('No owner data found, the deletion message cannot be processed.', ['user' => $uid]);
1918 if (empty($owner['uprvkey'])) {
1919 Logger::error('No private key for owner found, the deletion message cannot be processed.', ['user' => $uid]);
1923 $data = ['@context' => ActivityPub::CONTEXT,
1924 'id' => DI::baseUrl() . '/activity/' . System::createGUID(),
1926 'actor' => $owner['url'],
1927 'object' => $owner['url'],
1928 'published' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
1929 'instrument' => self::getService(),
1930 'to' => [ActivityPub::PUBLIC_COLLECTION],
1933 $signed = LDSignature::sign($data, $owner);
1935 Logger::info('Deliver profile deletion for user ' . $uid . ' to ' . $inbox . ' via ActivityPub');
1936 return HTTPSignature::transmit($signed, $inbox, $uid);
1940 * Transmits a profile change to a given inbox
1942 * @param integer $uid User ID
1943 * @param string $inbox Target inbox
1945 * @return boolean was the transmission successful?
1946 * @throws HTTPException\InternalServerErrorException
1947 * @throws HTTPException\NotFoundException
1948 * @throws \ImagickException
1950 public static function sendProfileUpdate(int $uid, string $inbox): bool
1952 $owner = User::getOwnerDataById($uid);
1953 $profile = APContact::getByURL($owner['url']);
1955 $data = ['@context' => ActivityPub::CONTEXT,
1956 'id' => DI::baseUrl() . '/activity/' . System::createGUID(),
1958 'actor' => $owner['url'],
1959 'object' => self::getProfile($uid),
1960 'published' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
1961 'instrument' => self::getService(),
1962 'to' => [$profile['followers']],
1965 $signed = LDSignature::sign($data, $owner);
1967 Logger::info('Deliver profile update for user ' . $uid . ' to ' . $inbox . ' via ActivityPub');
1968 return HTTPSignature::transmit($signed, $inbox, $uid);
1972 * Transmits a given activity to a target
1974 * @param string $activity Type name
1975 * @param string $target Target profile
1976 * @param integer $uid User ID
1978 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1979 * @throws \ImagickException
1980 * @throws \Exception
1982 public static function sendActivity($activity, $target, $uid, $id = '')
1984 $profile = APContact::getByURL($target);
1985 if (empty($profile['inbox'])) {
1986 Logger::warning('No inbox found for target', ['target' => $target, 'profile' => $profile]);
1990 $owner = User::getOwnerDataById($uid);
1993 $id = DI::baseUrl() . '/activity/' . System::createGUID();
1996 $data = ['@context' => ActivityPub::CONTEXT,
1998 'type' => $activity,
1999 'actor' => $owner['url'],
2000 'object' => $profile['url'],
2001 'instrument' => self::getService(),
2002 'to' => [$profile['url']]];
2004 Logger::info('Sending activity ' . $activity . ' to ' . $target . ' for user ' . $uid);
2006 $signed = LDSignature::sign($data, $owner);
2007 return HTTPSignature::transmit($signed, $profile['inbox'], $uid);
2011 * Transmits a "follow object" activity to a target
2012 * This is a preparation for sending automated "follow" requests when receiving "Announce" messages
2014 * @param string $object Object URL
2015 * @param string $target Target profile
2016 * @param integer $uid User ID
2018 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2019 * @throws \ImagickException
2020 * @throws \Exception
2022 public static function sendFollowObject($object, $target, $uid = 0)
2024 $profile = APContact::getByURL($target);
2025 if (empty($profile['inbox'])) {
2026 Logger::warning('No inbox found for target', ['target' => $target, 'profile' => $profile]);
2031 // Fetch the list of administrators
2032 $admin_mail = explode(',', str_replace(' ', '', DI::config()->get('config', 'admin_email')));
2034 // We need to use some user as a sender. It doesn't care who it will send. We will use an administrator account.
2035 $condition = ['verified' => true, 'blocked' => false, 'account_removed' => false, 'account_expired' => false, 'email' => $admin_mail];
2036 $first_user = DBA::selectFirst('user', ['uid'], $condition);
2037 $uid = $first_user['uid'];
2040 $condition = ['verb' => Activity::FOLLOW, 'uid' => 0, 'parent-uri' => $object,
2041 'author-id' => Contact::getPublicIdByUserId($uid)];
2042 if (Post::exists($condition)) {
2043 Logger::info('Follow for ' . $object . ' for user ' . $uid . ' does already exist.');
2047 $owner = User::getOwnerDataById($uid);
2049 $data = ['@context' => ActivityPub::CONTEXT,
2050 'id' => DI::baseUrl() . '/activity/' . System::createGUID(),
2052 'actor' => $owner['url'],
2053 'object' => $object,
2054 'instrument' => self::getService(),
2055 'to' => [$profile['url']]];
2057 Logger::info('Sending follow ' . $object . ' to ' . $target . ' for user ' . $uid);
2059 $signed = LDSignature::sign($data, $owner);
2060 return HTTPSignature::transmit($signed, $profile['inbox'], $uid);
2064 * Transmit a message that the contact request had been accepted
2066 * @param string $target Target profile
2068 * @param integer $uid User ID
2069 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2070 * @throws \ImagickException
2072 public static function sendContactAccept($target, $id, $uid)
2074 $profile = APContact::getByURL($target);
2075 if (empty($profile['inbox'])) {
2076 Logger::warning('No inbox found for target', ['target' => $target, 'profile' => $profile]);
2080 $owner = User::getOwnerDataById($uid);
2081 $data = ['@context' => ActivityPub::CONTEXT,
2082 'id' => DI::baseUrl() . '/activity/' . System::createGUID(),
2084 'actor' => $owner['url'],
2086 'id' => (string)$id,
2088 'actor' => $profile['url'],
2089 'object' => $owner['url']
2091 'instrument' => self::getService(),
2092 'to' => [$profile['url']]];
2094 Logger::debug('Sending accept to ' . $target . ' for user ' . $uid . ' with id ' . $id);
2096 $signed = LDSignature::sign($data, $owner);
2097 HTTPSignature::transmit($signed, $profile['inbox'], $uid);
2101 * Reject a contact request or terminates the contact relation
2103 * @param string $target Target profile
2105 * @param integer $uid User ID
2106 * @return bool Operation success
2107 * @throws HTTPException\InternalServerErrorException
2108 * @throws \ImagickException
2110 public static function sendContactReject($target, $id, $uid): bool
2112 $profile = APContact::getByURL($target);
2113 if (empty($profile['inbox'])) {
2114 Logger::warning('No inbox found for target', ['target' => $target, 'profile' => $profile]);
2118 $owner = User::getOwnerDataById($uid);
2119 $data = ['@context' => ActivityPub::CONTEXT,
2120 'id' => DI::baseUrl() . '/activity/' . System::createGUID(),
2122 'actor' => $owner['url'],
2124 'id' => (string)$id,
2126 'actor' => $profile['url'],
2127 'object' => $owner['url']
2129 'instrument' => self::getService(),
2130 'to' => [$profile['url']]];
2132 Logger::debug('Sending reject to ' . $target . ' for user ' . $uid . ' with id ' . $id);
2134 $signed = LDSignature::sign($data, $owner);
2135 return HTTPSignature::transmit($signed, $profile['inbox'], $uid);
2139 * Transmits a message that we don't want to follow this contact anymore
2141 * @param string $target Target profile
2142 * @param integer $uid User ID
2143 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2144 * @throws \ImagickException
2145 * @throws \Exception
2146 * @return bool success
2148 public static function sendContactUndo($target, $cid, $uid)
2150 $profile = APContact::getByURL($target);
2151 if (empty($profile['inbox'])) {
2152 Logger::warning('No inbox found for target', ['target' => $target, 'profile' => $profile]);
2156 $object_id = self::activityIDFromContact($cid);
2157 if (empty($object_id)) {
2161 $id = DI::baseUrl() . '/activity/' . System::createGUID();
2163 $owner = User::getOwnerDataById($uid);
2164 $data = ['@context' => ActivityPub::CONTEXT,
2167 'actor' => $owner['url'],
2168 'object' => ['id' => $object_id, 'type' => 'Follow',
2169 'actor' => $owner['url'],
2170 'object' => $profile['url']],
2171 'instrument' => self::getService(),
2172 'to' => [$profile['url']]];
2174 Logger::info('Sending undo to ' . $target . ' for user ' . $uid . ' with id ' . $id);
2176 $signed = LDSignature::sign($data, $owner);
2177 return HTTPSignature::transmit($signed, $profile['inbox'], $uid);
2180 private static function prependMentions($body, int $uriid, string $authorLink)
2184 foreach (Tag::getByURIId($uriid, [Tag::IMPLICIT_MENTION]) as $tag) {
2185 $profile = Contact::getByURL($tag['url'], false, ['addr', 'contact-type', 'nick']);
2186 if (!empty($profile['addr'])
2187 && $profile['contact-type'] != Contact::TYPE_COMMUNITY
2188 && !strstr($body, $profile['addr'])
2189 && !strstr($body, $tag['url'])
2190 && $tag['url'] !== $authorLink
2192 $mentions[] = '@[url=' . $tag['url'] . ']' . $profile['nick'] . '[/url]';
2196 $mentions[] = $body;
2198 return implode(' ', $mentions);