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
154 * @param boolean $nocache Wether to bypass caching
156 * @return array of owners
159 public static function getContacts(array $owner, array $rel, string $module, int $page = null, string $requester = null, $nocache = false)
162 $cachekey = 'transmitter:getContacts:' . $module . ':'. $owner['uid'];
163 $result = DI::cache()->get($cachekey);
164 if (!$nocache && !is_null($result)) {
171 'uid' => $owner['uid'],
180 $condition = DBA::mergeConditions($parameters, ["`url` IN (SELECT `url` FROM `apcontact`)"]);
182 $total = DBA::count('contact', $condition);
184 $modulePath = '/' . $module . '/';
186 $data = ['@context' => ActivityPub::CONTEXT];
187 $data['id'] = DI::baseUrl() . $modulePath . $owner['nickname'];
188 $data['type'] = 'OrderedCollection';
189 $data['totalItems'] = $total;
192 $data['id'] .= '?' . http_build_query(['page' => $page]);
195 // When we hide our friends we will only show the pure number but don't allow more.
196 $show_contacts = empty($owner['hide-friends']);
198 // Allow fetching the contact list when the requester is part of the list.
199 if (($owner['page-flags'] == User::PAGE_FLAGS_PRVGROUP) && !empty($requester)) {
200 $show_contacts = DBA::exists('contact', ['nurl' => Strings::normaliseLink($requester), 'uid' => $owner['uid'], 'blocked' => false]);
203 if (!$show_contacts) {
204 if (!empty($cachekey)) {
205 DI::cache()->set($cachekey, $data, Duration::QUARTER_HOUR);
212 $data['first'] = DI::baseUrl() . $modulePath . $owner['nickname'] . '?page=1';
214 $data['type'] = 'OrderedCollectionPage';
217 $contacts = DBA::select('contact', ['url'], $condition, ['limit' => [($page - 1) * 100, 100]]);
218 while ($contact = DBA::fetch($contacts)) {
219 $list[] = $contact['url'];
221 DBA::close($contacts);
223 if (count($list) == 100) {
224 $data['next'] = DI::baseUrl() . $modulePath . $owner['nickname'] . '?page=' . ($page + 1);
227 $data['partOf'] = DI::baseUrl() . $modulePath . $owner['nickname'];
229 $data['orderedItems'] = $list;
232 if (!empty($cachekey)) {
233 DI::cache()->set($cachekey, $data, Duration::QUARTER_HOUR);
240 * Public posts for the given owner
242 * @param array $owner Owner array
243 * @param integer $page Page number
244 * @param string $requester URL of requesting account
245 * @param boolean $nocache Wether to bypass caching
247 * @return array of posts
248 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
249 * @throws \ImagickException
251 public static function getOutbox(array $owner, int $page = null, string $requester = '', $nocache = false)
254 $cachekey = 'transmitter:getOutbox:' . $owner['uid'];
255 $result = DI::cache()->get($cachekey);
256 if (!$nocache && !is_null($result)) {
261 $condition = ['private' => [Item::PUBLIC, Item::UNLISTED]];
263 if (!empty($requester)) {
264 $requester_id = Contact::getIdForURL($requester, $owner['uid']);
265 if (!empty($requester_id)) {
266 $permissionSets = DI::permissionSet()->selectByContactId($requester_id, $owner['uid']);
267 if (!empty($permissionSets)) {
268 $condition = ['psid' => array_merge($permissionSets->column('id'),
269 [DI::permissionSet()->selectPublicForUser($owner['uid'])])];
274 $condition = array_merge($condition,
275 ['uid' => $owner['uid'],
276 'author-id' => Contact::getIdForURL($owner['url'], 0, false),
277 'gravity' => [GRAVITY_PARENT, GRAVITY_COMMENT],
278 'network' => Protocol::FEDERATED,
279 'parent-network' => Protocol::FEDERATED,
284 $count = Post::count($condition);
286 $data = ['@context' => ActivityPub::CONTEXT];
287 $data['id'] = DI::baseUrl() . '/outbox/' . $owner['nickname'];
288 $data['type'] = 'OrderedCollection';
289 $data['totalItems'] = $count;
292 $data['id'] .= '?' . http_build_query(['page' => $page]);
296 $data['first'] = DI::baseUrl() . '/outbox/' . $owner['nickname'] . '?page=1';
298 $data['type'] = 'OrderedCollectionPage';
301 $items = Post::select(['id'], $condition, ['limit' => [($page - 1) * 20, 20], 'order' => ['created' => true]]);
302 while ($item = Post::fetch($items)) {
303 $activity = self::createActivityFromItem($item['id'], true);
304 $activity['type'] = $activity['type'] == 'Update' ? 'Create' : $activity['type'];
306 // Only list "Create" activity objects here, no reshares
307 if (!empty($activity['object']) && ($activity['type'] == 'Create')) {
308 $list[] = $activity['object'];
313 if (count($list) == 20) {
314 $data['next'] = DI::baseUrl() . '/outbox/' . $owner['nickname'] . '?page=' . ($page + 1);
317 $data['partOf'] = DI::baseUrl() . '/outbox/' . $owner['nickname'];
319 $data['orderedItems'] = $list;
322 if (!empty($cachekey)) {
323 DI::cache()->set($cachekey, $data, Duration::QUARTER_HOUR);
330 * Public posts for the given owner
332 * @param array $owner Owner array
333 * @param integer $page Page number
334 * @param boolean $nocache Wether to bypass caching
336 * @return array of posts
337 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
338 * @throws \ImagickException
340 public static function getFeatured(array $owner, int $page = null, $nocache = false)
342 $owner_cid = Contact::getIdForURL($owner['url'], 0, false);
344 $cachekey = 'transmitter:getFeatured:' . $owner_cid;
345 $result = DI::cache()->get($cachekey);
346 if (!$nocache && !is_null($result)) {
351 $condition = ["`uri-id` IN (SELECT `uri-id` FROM `collection-view` WHERE `cid` = ? AND `type` = ?)",
352 $owner_cid, Post\Collection::FEATURED];
354 $condition = DBA::mergeConditions($condition,
355 ['uid' => $owner['uid'],
356 'author-id' => $owner_cid,
357 'private' => [Item::PUBLIC, Item::UNLISTED],
358 'gravity' => [GRAVITY_PARENT, GRAVITY_COMMENT],
359 'network' => Protocol::FEDERATED,
360 'parent-network' => Protocol::FEDERATED,
365 $count = Post::count($condition);
367 $data = ['@context' => ActivityPub::CONTEXT];
368 $data['id'] = DI::baseUrl() . '/featured/' . $owner['nickname'];
369 $data['type'] = 'OrderedCollection';
370 $data['totalItems'] = $count;
373 $data['id'] .= '?' . http_build_query(['page' => $page]);
377 $items = Post::select(['id'], $condition, ['limit' => 20, 'order' => ['created' => true]]);
379 $data['type'] = 'OrderedCollectionPage';
380 $items = Post::select(['id'], $condition, ['limit' => [($page - 1) * 20, 20], 'order' => ['created' => true]]);
384 while ($item = Post::fetch($items)) {
385 $activity = self::createActivityFromItem($item['id'], true);
386 $activity['type'] = $activity['type'] == 'Update' ? 'Create' : $activity['type'];
388 // Only list "Create" activity objects here, no reshares
389 if (!empty($activity['object']) && ($activity['type'] == 'Create')) {
390 $list[] = $activity['object'];
395 if (count($list) == 20) {
396 $data['next'] = DI::baseUrl() . '/featured/' . $owner['nickname'] . '?page=' . ($page + 1);
400 $data['partOf'] = DI::baseUrl() . '/featured/' . $owner['nickname'];
403 $data['orderedItems'] = $list;
405 if (!empty($cachekey)) {
406 DI::cache()->set($cachekey, $data, Duration::QUARTER_HOUR);
413 * Return the service array containing information the used software and it's url
415 * @return array with service data
417 private static function getService()
419 return ['type' => 'Service',
420 'name' => FRIENDICA_PLATFORM . " '" . FRIENDICA_CODENAME . "' " . FRIENDICA_VERSION . '-' . DB_UPDATE_VERSION,
421 'url' => DI::baseUrl()->get()];
425 * Return the ActivityPub profile of the given user
427 * @param int $uid User ID
428 * @return array with profile data
429 * @throws HTTPException\NotFoundException
430 * @throws HTTPException\InternalServerErrorException
432 public static function getProfile(int $uid): array
434 $owner = User::getOwnerDataById($uid);
435 if (!isset($owner['id'])) {
436 DI::logger()->error('Unable to find owner data for uid', ['uid' => $uid, 'callstack' => System::callstack(20)]);
437 throw new HTTPException\NotFoundException('User not found.');
440 $data = ['@context' => ActivityPub::CONTEXT];
441 $data['id'] = $owner['url'];
443 if (!empty($owner['guid'])) {
444 $data['diaspora:guid'] = $owner['guid'];
447 $data['type'] = ActivityPub::ACCOUNT_TYPES[$owner['account-type']];
450 $data['following'] = DI::baseUrl() . '/following/' . $owner['nick'];
451 $data['followers'] = DI::baseUrl() . '/followers/' . $owner['nick'];
452 $data['inbox'] = DI::baseUrl() . '/inbox/' . $owner['nick'];
453 $data['outbox'] = DI::baseUrl() . '/outbox/' . $owner['nick'];
454 $data['featured'] = DI::baseUrl() . '/featured/' . $owner['nick'];
456 $data['inbox'] = DI::baseUrl() . '/friendica/inbox';
459 $data['preferredUsername'] = $owner['nick'];
460 $data['name'] = $owner['name'];
462 if (!empty($owner['country-name'] . $owner['region'] . $owner['locality'])) {
463 $data['vcard:hasAddress'] = ['@type' => 'vcard:Home', 'vcard:country-name' => $owner['country-name'],
464 'vcard:region' => $owner['region'], 'vcard:locality' => $owner['locality']];
467 if (!empty($owner['about'])) {
468 $data['summary'] = BBCode::convertForUriId($owner['uri-id'] ?? 0, $owner['about'], BBCode::EXTERNAL);
471 if (!empty($owner['xmpp']) || !empty($owner['matrix'])) {
472 $data['vcard:hasInstantMessage'] = [];
474 if (!empty($owner['xmpp'])) {
475 $data['vcard:hasInstantMessage'][] = 'xmpp:' . $owner['xmpp'];
477 if (!empty($owner['matrix'])) {
478 $data['vcard:hasInstantMessage'][] = 'matrix:' . $owner['matrix'];
482 $data['url'] = $owner['url'];
483 $data['manuallyApprovesFollowers'] = in_array($owner['page-flags'], [User::PAGE_FLAGS_NORMAL, User::PAGE_FLAGS_PRVGROUP]);
484 $data['discoverable'] = (bool)$owner['net-publish'];
485 $data['publicKey'] = ['id' => $owner['url'] . '#main-key',
486 'owner' => $owner['url'],
487 'publicKeyPem' => $owner['pubkey']];
488 $data['endpoints'] = ['sharedInbox' => DI::baseUrl() . '/inbox'];
489 $data['icon'] = ['type' => 'Image', 'url' => User::getAvatarUrl($owner)];
491 $resourceid = Photo::ridFromURI($owner['photo']);
492 if (!empty($resourceid)) {
493 $photo = Photo::selectFirst(['type'], ["resource-id" => $resourceid]);
494 if (!empty($photo['type'])) {
495 $data['icon']['mediaType'] = $photo['type'];
499 if (!empty($owner['header'])) {
500 $data['image'] = ['type' => 'Image', 'url' => Contact::getHeaderUrlForId($owner['id'], '', $owner['updated'])];
502 $resourceid = Photo::ridFromURI($owner['header']);
503 if (!empty($resourceid)) {
504 $photo = Photo::selectFirst(['type'], ["resource-id" => $resourceid]);
505 if (!empty($photo['type'])) {
506 $data['image']['mediaType'] = $photo['type'];
513 foreach (DI::profileField()->selectByContactId(0, $uid) as $profile_field) {
515 'type' => 'PropertyValue',
516 'name' => $profile_field->label,
517 'value' => BBCode::convertForUriId($owner['uri-id'], $profile_field->value)
521 if (!empty($custom_fields)) {
522 $data['attachment'] = $custom_fields;
525 $data['generator'] = self::getService();
527 // tags: https://kitty.town/@inmysocks/100656097926961126.json
532 * @param string $username
534 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
536 public static function getDeletedUser($username)
539 '@context' => ActivityPub::CONTEXT,
540 'id' => DI::baseUrl() . '/profile/' . $username,
541 'type' => 'Tombstone',
542 'published' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
543 'updated' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
544 'deleted' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
549 * Returns an array with permissions of the thread parent of the given item array
552 * @param bool $is_forum_thread
554 * @return array with permissions
555 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
556 * @throws \ImagickException
558 private static function fetchPermissionBlockFromThreadParent(array $item, bool $is_forum_thread)
560 if (empty($item['thr-parent-id'])) {
564 $parent = Post::selectFirstPost(['author-link'], ['uri-id' => $item['thr-parent-id']]);
565 if (empty($parent)) {
570 'to' => [$parent['author-link']],
576 $parent_profile = APContact::getByURL($parent['author-link']);
578 $item_profile = APContact::getByURL($item['author-link']);
579 $exclude[] = $item['author-link'];
581 if ($item['gravity'] == GRAVITY_PARENT) {
582 $exclude[] = $item['owner-link'];
585 $type = [Tag::TO => 'to', Tag::CC => 'cc', Tag::BTO => 'bto', Tag::BCC => 'bcc'];
586 foreach (Tag::getByURIId($item['thr-parent-id'], [Tag::TO, Tag::CC, Tag::BTO, Tag::BCC]) as $receiver) {
587 if (!empty($parent_profile['followers']) && $receiver['url'] == $parent_profile['followers'] && !empty($item_profile['followers'])) {
588 if (!$is_forum_thread) {
589 $permissions[$type[$receiver['type']]][] = $item_profile['followers'];
591 } elseif (!in_array($receiver['url'], $exclude)) {
592 $permissions[$type[$receiver['type']]][] = $receiver['url'];
600 * Check if the given item id is from ActivityPub
602 * @param integer $item_id
603 * @return boolean "true" if the post is from ActivityPub
605 private static function isAPPost(int $item_id)
607 if (empty($item_id)) {
611 return Post::exists(['id' => $item_id, 'network' => Protocol::ACTIVITYPUB]);
615 * Creates an array of permissions from an item thread
617 * @param array $item Item array
618 * @param boolean $blindcopy addressing via "bcc" or "cc"?
619 * @param integer $last_id Last item id for adding receivers
621 * @return array with permission data
622 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
623 * @throws \ImagickException
625 private static function createPermissionBlockForItem($item, $blindcopy, $last_id = 0)
628 $last_id = $item['id'];
635 // Check if we should always deliver our stuff via BCC
636 if (!empty($item['uid'])) {
637 $owner = User::getOwnerDataById($item['uid']);
638 if (!empty($owner)) {
639 $always_bcc = $owner['hide-friends'];
640 $is_forum = ($owner['account-type'] == User::ACCOUNT_TYPE_COMMUNITY) && $owner['manually-approve'];
642 $profile = APContact::getByURL($owner['url'], false);
643 $follower = $profile['followers'] ?? '';
647 if (DI::config()->get('system', 'ap_always_bcc')) {
651 $parent = Post::selectFirst(['causer-link', 'post-reason'], ['id' => $item['parent']]);
652 if (($parent['post-reason'] == Item::PR_ANNOUNCEMENT) && !empty($parent['causer-link'])) {
653 $profile = APContact::getByURL($parent['causer-link'], false);
654 $is_forum_thread = isset($profile['type']) && $profile['type'] == 'Group';
656 $is_forum_thread = false;
659 if (self::isAnnounce($item) || DI::config()->get('debug', 'total_ap_delivery') || self::isAPPost($last_id)) {
660 // Will be activated in a later step
661 $networks = Protocol::FEDERATED;
663 // For now only send to these contacts:
664 $networks = [Protocol::ACTIVITYPUB, Protocol::OSTATUS];
667 $data = ['to' => [], 'cc' => [], 'bcc' => []];
669 if ($item['gravity'] == GRAVITY_PARENT) {
670 $actor_profile = APContact::getByURL($item['owner-link']);
672 $actor_profile = APContact::getByURL($item['author-link']);
677 $terms = Tag::getByURIId($item['uri-id'], [Tag::MENTION, Tag::IMPLICIT_MENTION, Tag::EXCLUSIVE_MENTION]);
679 if ($item['private'] != Item::PRIVATE) {
680 // Directly mention the original author upon a quoted reshare.
681 // Else just ensure that the original author receives the reshare.
682 $announce = self::getAnnounceArray($item);
683 if (!empty($announce['comment'])) {
684 $data['to'][] = $announce['actor']['url'];
685 } elseif (!empty($announce)) {
686 $data['cc'][] = $announce['actor']['url'];
689 $data = array_merge($data, self::fetchPermissionBlockFromThreadParent($item, $is_forum_thread));
691 // Check if the item is completely public or unlisted
692 if ($item['private'] == Item::PUBLIC) {
693 $data['to'][] = ActivityPub::PUBLIC_COLLECTION;
695 $data['cc'][] = ActivityPub::PUBLIC_COLLECTION;
698 foreach ($terms as $term) {
699 $profile = APContact::getByURL($term['url'], false);
700 if (!empty($profile)) {
701 if ($term['type'] == Tag::EXCLUSIVE_MENTION) {
703 if (!empty($profile['followers']) && ($profile['type'] == 'Group')) {
704 $data['cc'][] = $profile['followers'];
707 $data['to'][] = $profile['url'];
711 $receiver_list = Item::enumeratePermissions($item, true);
713 foreach ($terms as $term) {
714 $cid = Contact::getIdForURL($term['url'], $item['uid']);
715 if (!empty($cid) && in_array($cid, $receiver_list)) {
716 $contact = DBA::selectFirst('contact', ['url', 'network', 'protocol', 'gsid'], ['id' => $cid, 'network' => Protocol::FEDERATED]);
717 if (!DBA::isResult($contact) || !self::isAPContact($contact, $networks)) {
721 $profile = APContact::getByURL($term['url'], false);
722 if (!empty($profile)) {
723 if ($term['type'] == Tag::EXCLUSIVE_MENTION) {
725 if (!empty($profile['followers']) && ($profile['type'] == 'Group')) {
726 $data['cc'][] = $profile['followers'];
729 $data['to'][] = $profile['url'];
734 if ($is_forum && !$exclusive && !empty($follower)) {
735 $data['cc'][] = $follower;
736 } elseif (!$exclusive) {
737 foreach ($receiver_list as $receiver) {
738 $contact = DBA::selectFirst('contact', ['url', 'hidden', 'network', 'protocol', 'gsid'], ['id' => $receiver, 'network' => Protocol::FEDERATED]);
739 if (!DBA::isResult($contact) || !self::isAPContact($contact, $networks)) {
743 if (!empty($profile = APContact::getByURL($contact['url'], false))) {
744 if ($contact['hidden'] || $always_bcc) {
745 $data['bcc'][] = $profile['url'];
747 $data['cc'][] = $profile['url'];
754 if (!empty($item['parent'])) {
755 $parents = Post::select(['id', 'author-link', 'owner-link', 'gravity', 'uri'], ['parent' => $item['parent']], ['order' => ['id']]);
756 while ($parent = Post::fetch($parents)) {
757 if ($parent['gravity'] == GRAVITY_PARENT) {
758 $profile = APContact::getByURL($parent['owner-link'], false);
759 if (!empty($profile)) {
760 if ($item['gravity'] != GRAVITY_PARENT) {
761 // Comments to forums are directed to the forum
762 // But comments to forums aren't directed to the followers collection
763 // This rule is only valid when the actor isn't the forum.
764 // The forum needs to transmit their content to their followers.
765 if (($profile['type'] == 'Group') && ($profile['url'] != ($actor_profile['url'] ?? ''))) {
766 $data['to'][] = $profile['url'];
768 $data['cc'][] = $profile['url'];
769 if (($item['private'] != Item::PRIVATE) && !empty($actor_profile['followers'])&& !$is_forum_thread) {
770 $data['cc'][] = $actor_profile['followers'];
773 } elseif (!$exclusive && !$is_forum_thread) {
774 // Public thread parent post always are directed to the followers.
775 if ($item['private'] != Item::PRIVATE) {
776 $data['cc'][] = $actor_profile['followers'];
782 // Don't include data from future posts
783 if ($parent['id'] >= $last_id) {
787 $profile = APContact::getByURL($parent['author-link'], false);
788 if (!empty($profile)) {
789 if (($profile['type'] == 'Group') || ($parent['uri'] == $item['thr-parent'])) {
790 $data['to'][] = $profile['url'];
792 $data['cc'][] = $profile['url'];
796 DBA::close($parents);
799 $data['to'] = array_unique($data['to']);
800 $data['cc'] = array_unique($data['cc']);
801 $data['bcc'] = array_unique($data['bcc']);
803 if (($key = array_search($item['author-link'], $data['to'])) !== false) {
804 unset($data['to'][$key]);
807 if (($key = array_search($item['author-link'], $data['cc'])) !== false) {
808 unset($data['cc'][$key]);
811 if (($key = array_search($item['author-link'], $data['bcc'])) !== false) {
812 unset($data['bcc'][$key]);
815 foreach ($data['to'] as $to) {
816 if (($key = array_search($to, $data['cc'])) !== false) {
817 unset($data['cc'][$key]);
820 if (($key = array_search($to, $data['bcc'])) !== false) {
821 unset($data['bcc'][$key]);
825 foreach ($data['cc'] as $cc) {
826 if (($key = array_search($cc, $data['bcc'])) !== false) {
827 unset($data['bcc'][$key]);
831 $receivers = ['to' => array_values($data['to']), 'cc' => array_values($data['cc']), 'bcc' => array_values($data['bcc'])];
834 unset($receivers['bcc']);
837 foreach (['to' => Tag::TO, 'cc' => Tag::CC, 'bcc' => Tag::BCC] as $element => $type) {
838 if (!empty($receivers[$element])) {
839 foreach ($receivers[$element] as $receiver) {
840 if ($receiver == ActivityPub::PUBLIC_COLLECTION) {
841 $name = Receiver::PUBLIC_COLLECTION;
843 $name = trim(parse_url($receiver, PHP_URL_PATH), '/');
845 Tag::store($item['uri-id'], $type, $name, $receiver);
854 * Check if an inbox is archived
856 * @param string $url Inbox url
858 * @return boolean "true" if inbox is archived
860 public static function archivedInbox($url)
862 return DBA::exists('inbox-status', ['url' => $url, 'archive' => true]);
866 * Check if a given contact should be delivered via AP
868 * @param array $contact
869 * @param array $networks
873 private static function isAPContact(array $contact, array $networks)
875 if (in_array($contact['network'], $networks) || ($contact['protocol'] == Protocol::ACTIVITYPUB)) {
879 return GServer::getProtocol($contact['gsid'] ?? 0) == Post\DeliveryData::ACTIVITYPUB;
883 * Fetches a list of inboxes of followers of a given user
885 * @param integer $uid User ID
886 * @param boolean $personal fetch personal inboxes
887 * @param boolean $all_ap Retrieve all AP enabled inboxes
889 * @return array of follower inboxes
890 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
891 * @throws \ImagickException
893 public static function fetchTargetInboxesforUser($uid, $personal = false, bool $all_ap = false)
899 if (!empty($item['uid'])) {
900 $profile = User::getOwnerDataById($item['uid']);
901 if (!empty($profile)) {
902 $isforum = $profile['account-type'] == User::ACCOUNT_TYPE_COMMUNITY;
906 if (DI::config()->get('debug', 'total_ap_delivery') || $all_ap) {
907 // Will be activated in a later step
908 $networks = Protocol::FEDERATED;
910 // For now only send to these contacts:
911 $networks = [Protocol::ACTIVITYPUB, Protocol::OSTATUS];
914 $condition = ['uid' => $uid, 'archive' => false, 'pending' => false, 'blocked' => false, 'network' => Protocol::FEDERATED];
917 $condition['rel'] = [Contact::FOLLOWER, Contact::FRIEND];
920 $contacts = DBA::select('contact', ['id', 'url', 'network', 'protocol', 'gsid'], $condition);
921 while ($contact = DBA::fetch($contacts)) {
922 if (!self::isAPContact($contact, $networks)) {
926 if ($isforum && ($contact['network'] == Protocol::DFRN)) {
930 if (Network::isUrlBlocked($contact['url'])) {
934 $profile = APContact::getByURL($contact['url'], false);
935 if (!empty($profile)) {
936 if (empty($profile['sharedinbox']) || $personal || Contact::isLocal($contact['url'])) {
937 $target = $profile['inbox'];
939 $target = $profile['sharedinbox'];
941 if (!self::archivedInbox($target)) {
942 $inboxes[$target][] = $contact['id'];
946 DBA::close($contacts);
952 * Fetches an array of inboxes for the given item and user
954 * @param array $item Item array
955 * @param integer $uid User ID
956 * @param boolean $personal fetch personal inboxes
957 * @param integer $last_id Last item id for adding receivers
958 * @return array with inboxes
959 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
960 * @throws \ImagickException
962 public static function fetchTargetInboxes($item, $uid, $personal = false, $last_id = 0)
964 $permissions = self::createPermissionBlockForItem($item, true, $last_id);
965 if (empty($permissions)) {
971 if ($item['gravity'] == GRAVITY_ACTIVITY) {
972 $item_profile = APContact::getByURL($item['author-link'], false);
974 $item_profile = APContact::getByURL($item['owner-link'], false);
977 if (empty($item_profile)) {
981 $profile_uid = User::getIdForURL($item_profile['url']);
983 foreach (['to', 'cc', 'bto', 'bcc'] as $element) {
984 if (empty($permissions[$element])) {
988 $blindcopy = in_array($element, ['bto', 'bcc']);
990 foreach ($permissions[$element] as $receiver) {
991 if (empty($receiver) || Network::isUrlBlocked($receiver)) {
995 if ($item_profile && ($receiver == $item_profile['followers']) && ($uid == $profile_uid)) {
996 $inboxes = array_merge($inboxes, self::fetchTargetInboxesforUser($uid, $personal, self::isAPPost($last_id)));
998 $profile = APContact::getByURL($receiver, false);
999 if (!empty($profile)) {
1000 $contact = Contact::getByURLForUser($receiver, $uid, false, ['id']);
1002 if (empty($profile['sharedinbox']) || $personal || $blindcopy || Contact::isLocal($receiver)) {
1003 $target = $profile['inbox'];
1005 $target = $profile['sharedinbox'];
1007 if (!self::archivedInbox($target)) {
1008 $inboxes[$target][] = $contact['id'] ?? 0;
1019 * Creates an array in the structure of the item table for a given mail id
1021 * @param integer $mail_id
1024 * @throws \Exception
1026 public static function ItemArrayFromMail($mail_id, $use_title = false)
1028 $mail = DBA::selectFirst('mail', [], ['id' => $mail_id]);
1029 if (!DBA::isResult($mail)) {
1033 $reply = DBA::selectFirst('mail', ['uri', 'uri-id', 'from-url'], ['parent-uri' => $mail['parent-uri'], 'reply' => false]);
1034 if (!DBA::isResult($reply)) {
1038 // Making the post more compatible for Mastodon by:
1039 // - Making it a note and not an article (no title)
1040 // - Moving the title into the "summary" field that is used as a "content warning"
1043 $mail['body'] = '[abstract]' . $mail['title'] . "[/abstract]\n" . $mail['body'];
1044 $mail['title'] = '';
1047 $mail['content-warning'] = '';
1048 $mail['author-link'] = $mail['owner-link'] = $mail['from-url'];
1049 $mail['owner-id'] = $mail['author-id'];
1050 $mail['allow_cid'] = '<'.$mail['contact-id'].'>';
1051 $mail['allow_gid'] = '';
1052 $mail['deny_cid'] = '';
1053 $mail['deny_gid'] = '';
1054 $mail['private'] = Item::PRIVATE;
1055 $mail['deleted'] = false;
1056 $mail['edited'] = $mail['created'];
1057 $mail['plink'] = DI::baseUrl() . '/message/' . $mail['id'];
1058 $mail['parent-uri'] = $reply['uri'];
1059 $mail['parent-uri-id'] = $reply['uri-id'];
1060 $mail['parent-author-id'] = Contact::getIdForURL($reply['from-url'], 0, false);
1061 $mail['gravity'] = ($mail['reply'] ? GRAVITY_COMMENT: GRAVITY_PARENT);
1062 $mail['event-type'] = '';
1063 $mail['language'] = '';
1064 $mail['parent'] = 0;
1070 * Creates an activity array for a given mail id
1072 * @param integer $mail_id
1073 * @param boolean $object_mode Is the activity item is used inside another object?
1075 * @return array of activity
1076 * @throws \Exception
1078 public static function createActivityFromMail($mail_id, $object_mode = false)
1080 $mail = self::ItemArrayFromMail($mail_id);
1084 $object = self::createNote($mail);
1086 if (!$object_mode) {
1087 $data = ['@context' => ActivityPub::CONTEXT];
1092 $data['id'] = $mail['uri'] . '/Create';
1093 $data['type'] = 'Create';
1094 $data['actor'] = $mail['author-link'];
1095 $data['published'] = DateTimeFormat::utc($mail['created'] . '+00:00', DateTimeFormat::ATOM);
1096 $data['instrument'] = self::getService();
1097 $data = array_merge($data, self::createPermissionBlockForItem($mail, true));
1099 if (empty($data['to']) && !empty($data['cc'])) {
1100 $data['to'] = $data['cc'];
1103 if (empty($data['to']) && !empty($data['bcc'])) {
1104 $data['to'] = $data['bcc'];
1108 unset($data['bcc']);
1110 $object['to'] = $data['to'];
1111 $object['tag'] = [['type' => 'Mention', 'href' => $object['to'][0], 'name' => '']];
1113 unset($object['cc']);
1114 unset($object['bcc']);
1116 $data['directMessage'] = true;
1118 $data['object'] = $object;
1120 $owner = User::getOwnerDataById($mail['uid']);
1122 if (!$object_mode && !empty($owner)) {
1123 return LDSignature::sign($data, $owner);
1130 * Returns the activity type of a given item
1132 * @param array $item
1134 * @return string with activity type
1135 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1136 * @throws \ImagickException
1138 private static function getTypeOfItem($item)
1142 // Only check for a reshare, if it is a real reshare and no quoted reshare
1143 if (strpos($item['body'], "[share") === 0) {
1144 $announce = self::getAnnounceArray($item);
1145 $reshared = !empty($announce);
1150 } elseif ($item['verb'] == Activity::POST) {
1151 if ($item['created'] == $item['edited']) {
1156 } elseif ($item['verb'] == Activity::LIKE) {
1158 } elseif ($item['verb'] == Activity::DISLIKE) {
1160 } elseif ($item['verb'] == Activity::ATTEND) {
1162 } elseif ($item['verb'] == Activity::ATTENDNO) {
1164 } elseif ($item['verb'] == Activity::ATTENDMAYBE) {
1165 $type = 'TentativeAccept';
1166 } elseif ($item['verb'] == Activity::FOLLOW) {
1168 } elseif ($item['verb'] == Activity::TAG) {
1170 } elseif ($item['verb'] == Activity::ANNOUNCE) {
1180 * Creates the activity or fetches it from the cache
1182 * @param integer $item_id
1183 * @param boolean $force Force new cache entry
1185 * @return array with the activity
1186 * @throws \Exception
1188 public static function createCachedActivityFromItem($item_id, $force = false)
1190 $cachekey = 'APDelivery:createActivity:' . $item_id;
1193 $data = DI::cache()->get($cachekey);
1194 if (!is_null($data)) {
1199 $data = self::createActivityFromItem($item_id);
1201 DI::cache()->set($cachekey, $data, Duration::QUARTER_HOUR);
1206 * Creates an activity array for a given item id
1208 * @param integer $item_id
1209 * @param boolean $object_mode Is the activity item is used inside another object?
1211 * @return false|array
1212 * @throws \Exception
1214 public static function createActivityFromItem(int $item_id, bool $object_mode = false)
1216 Logger::info('Fetching activity', ['item' => $item_id]);
1217 $item = Post::selectFirst(Item::DELIVER_FIELDLIST, ['id' => $item_id, 'parent-network' => Protocol::NATIVE_SUPPORT]);
1218 if (!DBA::isResult($item)) {
1222 if (empty($item['uri-id'])) {
1223 Logger::warning('Item without uri-id', ['item' => $item]);
1227 if (!$item['deleted']) {
1228 $condition = ['item-uri' => $item['uri'], 'protocol' => Conversation::PARCEL_ACTIVITYPUB];
1229 $conversation = DBA::selectFirst('conversation', ['source'], $condition);
1230 if (!$item['origin'] && DBA::isResult($conversation)) {
1231 $data = json_decode($conversation['source'], true);
1232 if (!empty($data['type'])) {
1233 if (in_array($data['type'], ['Create', 'Update'])) {
1235 unset($data['@context']);
1236 unset($data['signature']);
1238 Logger::info('Return stored conversation', ['item' => $item_id]);
1240 } elseif (in_array('as:' . $data['type'], Receiver::CONTENT_TYPES)) {
1241 if (!empty($data['@context'])) {
1242 $context = $data['@context'];
1243 unset($data['@context']);
1245 unset($data['actor']);
1252 $type = self::getTypeOfItem($item);
1254 if (!$object_mode) {
1255 $data = ['@context' => $context ?? ActivityPub::CONTEXT];
1257 if ($item['deleted'] && ($item['gravity'] == GRAVITY_ACTIVITY)) {
1259 } elseif ($item['deleted']) {
1266 if ($type == 'Delete') {
1267 $data['id'] = Item::newURI($item['uid'], $item['guid']) . '/' . $type;;
1268 } elseif (($item['gravity'] == GRAVITY_ACTIVITY) && ($type != 'Undo')) {
1269 $data['id'] = $item['uri'];
1271 $data['id'] = $item['uri'] . '/' . $type;
1274 $data['type'] = $type;
1276 if (($type != 'Announce') || ($item['gravity'] != GRAVITY_PARENT)) {
1277 $data['actor'] = $item['author-link'];
1279 $data['actor'] = $item['owner-link'];
1282 $data['published'] = DateTimeFormat::utc($item['created'] . '+00:00', DateTimeFormat::ATOM);
1284 $data['instrument'] = self::getService();
1286 $data = array_merge($data, self::createPermissionBlockForItem($item, false));
1288 if (in_array($data['type'], ['Create', 'Update', 'Delete'])) {
1289 $data['object'] = $object ?? self::createNote($item);
1290 $data['published'] = DateTimeFormat::utcNow(DateTimeFormat::ATOM);
1291 } elseif ($data['type'] == 'Add') {
1292 $data = self::createAddTag($item, $data);
1293 } elseif ($data['type'] == 'Announce') {
1294 if ($item['verb'] == ACTIVITY::ANNOUNCE) {
1295 $data['object'] = $item['thr-parent'];
1297 $data = self::createAnnounce($item, $data);
1299 } elseif ($data['type'] == 'Follow') {
1300 $data['object'] = $item['parent-uri'];
1301 } elseif ($data['type'] == 'Undo') {
1302 $data['object'] = self::createActivityFromItem($item_id, true);
1304 $data['diaspora:guid'] = $item['guid'];
1305 if (!empty($item['signed_text'])) {
1306 $data['diaspora:like'] = $item['signed_text'];
1308 $data['object'] = $item['thr-parent'];
1311 if (!empty($item['contact-uid'])) {
1312 $uid = $item['contact-uid'];
1314 $uid = $item['uid'];
1317 $owner = User::getOwnerDataById($uid);
1319 Logger::info('Fetched activity', ['item' => $item_id, 'uid' => $uid]);
1321 // We don't sign if we aren't the actor. This is important for relaying content especially for forums
1322 if (!$object_mode && !empty($owner) && ($data['actor'] == $owner['url'])) {
1323 return LDSignature::sign($data, $owner);
1328 /// @todo Create "conversation" entry
1332 * Creates a location entry for a given item array
1334 * @param array $item
1336 * @return array with location array
1338 private static function createLocation($item)
1340 $location = ['type' => 'Place'];
1342 if (!empty($item['location'])) {
1343 $location['name'] = $item['location'];
1348 if (empty($item['coord'])) {
1349 $coord = Map::getCoordinates($item['location']);
1351 $coords = explode(' ', $item['coord']);
1352 if (count($coords) == 2) {
1353 $coord = ['lat' => $coords[0], 'lon' => $coords[1]];
1357 if (!empty($coord['lat']) && !empty($coord['lon'])) {
1358 $location['latitude'] = $coord['lat'];
1359 $location['longitude'] = $coord['lon'];
1366 * Returns a tag array for a given item array
1368 * @param array $item
1370 * @return array of tags
1371 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1373 private static function createTagList($item)
1377 $terms = Tag::getByURIId($item['uri-id'], [Tag::HASHTAG, Tag::MENTION, Tag::IMPLICIT_MENTION, Tag::EXCLUSIVE_MENTION]);
1378 foreach ($terms as $term) {
1379 if ($term['type'] == Tag::HASHTAG) {
1380 $url = DI::baseUrl() . '/search?tag=' . urlencode($term['name']);
1381 $tags[] = ['type' => 'Hashtag', 'href' => $url, 'name' => '#' . $term['name']];
1383 $contact = Contact::getByURL($term['url'], false, ['addr']);
1384 if (empty($contact)) {
1387 if (!empty($contact['addr'])) {
1388 $mention = '@' . $contact['addr'];
1390 $mention = '@' . $term['url'];
1393 $tags[] = ['type' => 'Mention', 'href' => $term['url'], 'name' => $mention];
1397 $announce = self::getAnnounceArray($item);
1398 // Mention the original author upon commented reshares
1399 if (!empty($announce['comment'])) {
1400 $tags[] = ['type' => 'Mention', 'href' => $announce['actor']['url'], 'name' => '@' . $announce['actor']['addr']];
1407 * Adds attachment data to the JSON document
1409 * @param array $item Data of the item that is to be posted
1410 * @param string $type Object type
1412 * @return array with attachment data
1413 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1415 private static function createAttachmentList($item, $type)
1419 $uriids = [$item['uri-id']];
1420 $shared = BBCode::fetchShareAttributes($item['body']);
1421 if (!empty($shared['guid'])) {
1422 $shared_item = Post::selectFirst(['uri-id'], ['guid' => $shared['guid']]);
1423 if (!empty($shared_item['uri-id'])) {
1424 $uriids[] = $shared_item['uri-id'];
1429 foreach ($uriids as $uriid) {
1430 foreach (Post\Media::getByURIId($uriid, [Post\Media::AUDIO, Post\Media::IMAGE, Post\Media::VIDEO, Post\Media::DOCUMENT, Post\Media::TORRENT]) as $attachment) {
1431 if (in_array($attachment['url'], $urls)) {
1434 $urls[] = $attachment['url'];
1436 $attach = ['type' => 'Document',
1437 'mediaType' => $attachment['mimetype'],
1438 'url' => $attachment['url'],
1439 'name' => $attachment['description']];
1441 if (!empty($attachment['height'])) {
1442 $attach['height'] = $attachment['height'];
1445 if (!empty($attachment['width'])) {
1446 $attach['width'] = $attachment['width'];
1449 if (!empty($attachment['preview'])) {
1450 $attach['image'] = $attachment['preview'];
1453 $attachments[] = $attach;
1457 return $attachments;
1461 * Callback function to replace a Friendica style mention in a mention for a summary
1463 * @param array $match Matching values for the callback
1464 * @return string Replaced mention
1465 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1467 private static function mentionAddrCallback($match)
1469 if (empty($match[1])) {
1473 $data = Contact::getByURL($match[1], false, ['addr']);
1474 if (empty($data['addr'])) {
1478 return '@' . $data['addr'];
1482 * Remove image elements since they are added as attachment
1484 * @param string $body
1486 * @return string with removed images
1488 private static function removePictures($body)
1490 // Simplify image codes
1491 $body = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '[img]$3[/img]', $body);
1492 $body = preg_replace("/\[img\=(.*?)\](.*?)\[\/img\]/ism", '[img]$1[/img]', $body);
1494 // Now remove local links
1495 $body = preg_replace_callback(
1496 '/\[url=([^\[\]]*)\]\[img\](.*)\[\/img\]\[\/url\]/Usi',
1498 // We remove the link when it is a link to a local photo page
1499 if (Photo::isLocalPage($match[1])) {
1502 // otherwise we just return the link
1503 return '[url]' . $match[1] . '[/url]';
1508 // Remove all pictures
1509 $body = preg_replace("/\[img\]([^\[\]]*)\[\/img\]/Usi", '', $body);
1515 * Fetches the "context" value for a givem item array from the "conversation" table
1517 * @param array $item
1519 * @return string with context url
1520 * @throws \Exception
1522 private static function fetchContextURLForItem($item)
1524 $conversation = DBA::selectFirst('conversation', ['conversation-href', 'conversation-uri'], ['item-uri' => $item['parent-uri']]);
1525 if (DBA::isResult($conversation) && !empty($conversation['conversation-href'])) {
1526 $context_uri = $conversation['conversation-href'];
1527 } elseif (DBA::isResult($conversation) && !empty($conversation['conversation-uri'])) {
1528 $context_uri = $conversation['conversation-uri'];
1530 $context_uri = $item['parent-uri'] . '#context';
1532 return $context_uri;
1536 * Returns if the post contains sensitive content ("nsfw")
1538 * @param integer $uri_id
1541 * @throws \Exception
1543 private static function isSensitive($uri_id)
1545 return DBA::exists('tag-view', ['uri-id' => $uri_id, 'name' => 'nsfw', 'type' => Tag::HASHTAG]);
1549 * Creates event data
1551 * @param array $item
1553 * @return array with the event data
1554 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1556 private static function createEvent($item)
1559 $event['name'] = $item['event-summary'];
1560 $event['content'] = BBCode::convertForUriId($item['uri-id'], $item['event-desc'], BBCode::ACTIVITYPUB);
1561 $event['startTime'] = DateTimeFormat::utc($item['event-start'], 'c');
1563 if (!$item['event-nofinish']) {
1564 $event['endTime'] = DateTimeFormat::utc($item['event-finish'], 'c');
1567 if (!empty($item['event-location'])) {
1568 $item['location'] = $item['event-location'];
1569 $event['location'] = self::createLocation($item);
1572 // 2021.12: Backward compatibility value, all the events now "adjust" to the viewer timezone
1573 $event['dfrn:adjust'] = true;
1579 * Creates a note/article object array
1581 * @param array $item
1583 * @return array with the object data
1584 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1585 * @throws \ImagickException
1587 public static function createNote($item)
1593 // We are treating posts differently when they are directed to a community.
1594 // This is done to better support Lemmy. Most of the changes should work with other systems as well.
1595 // But to not risk compatibility issues we currently perform the changes only for communities.
1596 if ($item['gravity'] == GRAVITY_PARENT) {
1597 $isCommunityPost = !empty(Tag::getByURIId($item['uri-id'], [Tag::EXCLUSIVE_MENTION]));
1598 $links = Post\Media::getByURIId($item['uri-id'], [Post\Media::HTML]);
1599 if ($isCommunityPost && (count($links) == 1)) {
1600 $link = $links[0]['url'];
1603 $isCommunityPost = false;
1606 if ($item['event-type'] == 'event') {
1608 } elseif (!empty($item['title'])) {
1609 if (!$isCommunityPost || empty($link)) {
1612 // "Page" is used by Lemmy for posts that contain an external link
1619 if ($item['deleted']) {
1620 $type = 'Tombstone';
1624 $data['id'] = $item['uri'];
1625 $data['type'] = $type;
1627 if ($item['deleted']) {
1631 $data['summary'] = BBCode::toPlaintext(BBCode::getAbstract($item['body'], Protocol::ACTIVITYPUB));
1633 if ($item['uri'] != $item['thr-parent']) {
1634 $data['inReplyTo'] = $item['thr-parent'];
1636 $data['inReplyTo'] = null;
1639 $data['diaspora:guid'] = $item['guid'];
1640 $data['published'] = DateTimeFormat::utc($item['created'] . '+00:00', DateTimeFormat::ATOM);
1642 if ($item['created'] != $item['edited']) {
1643 $data['updated'] = DateTimeFormat::utc($item['edited'] . '+00:00', DateTimeFormat::ATOM);
1646 $data['url'] = $link ?? $item['plink'];
1647 $data['attributedTo'] = $item['author-link'];
1648 $data['sensitive'] = self::isSensitive($item['uri-id']);
1649 $data['context'] = self::fetchContextURLForItem($item);
1651 if (!empty($item['title'])) {
1652 $data['name'] = BBCode::toPlaintext($item['title'], false);
1655 $permission_block = self::createPermissionBlockForItem($item, false);
1657 $body = $item['body'];
1659 if ($type == 'Note') {
1660 $body = $item['raw-body'] ?? self::removePictures($body);
1664 * @todo Improve the automated summary
1665 * This part is currently deactivated. The automated summary seems to be more
1666 * confusing than helping. But possibly we will find a better way.
1667 * So the code is left here for now as a reminder
1669 * } elseif (($type == 'Article') && empty($data['summary'])) {
1670 * $regexp = "/[@!]\[url\=([^\[\]]*)\].*?\[\/url\]/ism";
1671 * $summary = preg_replace_callback($regexp, ['self', 'mentionAddrCallback'], $body);
1672 * $data['summary'] = BBCode::toPlaintext(Plaintext::shorten(self::removePictures($summary), 1000));
1676 if (empty($item['uid']) || !Feature::isEnabled($item['uid'], 'explicit_mentions')) {
1677 $body = self::prependMentions($body, $item['uri-id'], $item['author-link']);
1680 if ($type == 'Event') {
1681 $data = array_merge($data, self::createEvent($item));
1683 if ($isCommunityPost) {
1684 // For community posts we remove the visible "!user@domain.tld".
1685 // This improves the look at systems like Lemmy.
1686 // Also in the future we should control the community delivery via other methods.
1687 $body = preg_replace("/!\[url\=[^\[\]]*\][^\[\]]*\[\/url\]/ism", '', $body);
1690 if ($type == 'Page') {
1691 // When we transmit "Page" posts we have to remove the attachment.
1692 // The attachment contains the link that we already transmit in the "url" field.
1693 $body = preg_replace("/\s*\[attachment .*?\].*?\[\/attachment\]\s*/ism", '', $body);
1696 $body = BBCode::setMentionsToNicknames($body);
1698 $data['content'] = BBCode::convertForUriId($item['uri-id'], $body, BBCode::ACTIVITYPUB);
1701 // The regular "content" field does contain a minimized HTML. This is done since systems like
1702 // Mastodon has got problems with - for example - embedded pictures.
1703 // The contentMap does contain the unmodified HTML.
1704 $language = self::getLanguage($item);
1705 if (!empty($language)) {
1706 $richbody = BBCode::setMentionsToNicknames($item['body'] ?? '');
1707 $richbody = BBCode::removeAttachment($richbody);
1709 $data['contentMap'][$language] = BBCode::convertForUriId($item['uri-id'], $richbody, BBCode::EXTERNAL);
1712 $data['source'] = ['content' => $item['body'], 'mediaType' => "text/bbcode"];
1714 if (!empty($item['signed_text']) && ($item['uri'] != $item['thr-parent'])) {
1715 $data['diaspora:comment'] = $item['signed_text'];
1718 $data['attachment'] = self::createAttachmentList($item, $type);
1719 $data['tag'] = self::createTagList($item);
1721 if (empty($data['location']) && (!empty($item['coord']) || !empty($item['location']))) {
1722 $data['location'] = self::createLocation($item);
1725 if (!empty($item['app'])) {
1726 $data['generator'] = ['type' => 'Application', 'name' => $item['app']];
1729 $data = array_merge($data, $permission_block);
1735 * Fetches the language from the post, the user or the system.
1737 * @param array $item
1739 * @return string language string
1741 private static function getLanguage(array $item)
1743 // Try to fetch the language from the post itself
1744 if (!empty($item['language'])) {
1745 $languages = array_keys(json_decode($item['language'], true));
1746 if (!empty($languages[0])) {
1747 return $languages[0];
1751 // Otherwise use the user's language
1752 if (!empty($item['uid'])) {
1753 $user = DBA::selectFirst('user', ['language'], ['uid' => $item['uid']]);
1754 if (!empty($user['language'])) {
1755 return $user['language'];
1759 // And finally just use the system language
1760 return DI::config()->get('system', 'language');
1764 * Creates an an "add tag" entry
1766 * @param array $item
1767 * @param array $data activity data
1769 * @return array with activity data for adding tags
1770 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1771 * @throws \ImagickException
1773 private static function createAddTag($item, $data)
1775 $object = XML::parseString($item['object']);
1776 $target = XML::parseString($item["target"]);
1778 $data['diaspora:guid'] = $item['guid'];
1779 $data['actor'] = $item['author-link'];
1780 $data['target'] = (string)$target->id;
1781 $data['summary'] = BBCode::toPlaintext($item['body']);
1782 $data['object'] = ['id' => (string)$object->id, 'type' => 'tag', 'name' => (string)$object->title, 'content' => (string)$object->content];
1788 * Creates an announce object entry
1790 * @param array $item
1791 * @param array $data activity data
1793 * @return array with activity data
1794 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1795 * @throws \ImagickException
1797 private static function createAnnounce($item, $data)
1799 $orig_body = $item['body'];
1800 $announce = self::getAnnounceArray($item);
1801 if (empty($announce)) {
1802 $data['type'] = 'Create';
1803 $data['object'] = self::createNote($item);
1807 if (empty($announce['comment'])) {
1808 // Pure announce, without a quote
1809 $data['type'] = 'Announce';
1810 $data['object'] = $announce['object']['uri'];
1815 $data['type'] = 'Create';
1816 $item['body'] = $announce['comment'] . "\n" . $announce['object']['plink'];
1817 $data['object'] = self::createNote($item);
1819 /// @todo Finally descide how to implement this in AP. This is a possible way:
1820 $data['object']['attachment'][] = self::createNote($announce['object']);
1822 $data['object']['source']['content'] = $orig_body;
1827 * Return announce related data if the item is an annunce
1829 * @param array $item
1833 public static function getAnnounceArray($item)
1835 $reshared = Item::getShareArray($item);
1836 if (empty($reshared['guid'])) {
1840 $reshared_item = Post::selectFirst(Item::DELIVER_FIELDLIST, ['guid' => $reshared['guid']]);
1841 if (!DBA::isResult($reshared_item)) {
1845 if (!in_array($reshared_item['network'], [Protocol::ACTIVITYPUB, Protocol::DFRN])) {
1849 $profile = APContact::getByURL($reshared_item['author-link'], false);
1850 if (empty($profile)) {
1854 return ['object' => $reshared_item, 'actor' => $profile, 'comment' => $reshared['comment']];
1858 * Checks if the provided item array is an announce
1860 * @param array $item
1864 public static function isAnnounce($item)
1866 if (!empty($item['verb']) && ($item['verb'] == Activity::ANNOUNCE)) {
1870 $announce = self::getAnnounceArray($item);
1871 if (empty($announce)) {
1875 return empty($announce['comment']);
1879 * Creates an activity id for a given contact id
1881 * @param integer $cid Contact ID of target
1883 * @return bool|string activity id
1885 public static function activityIDFromContact($cid)
1887 $contact = DBA::selectFirst('contact', ['uid', 'id', 'created'], ['id' => $cid]);
1888 if (!DBA::isResult($contact)) {
1892 $hash = hash('ripemd128', $contact['uid'].'-'.$contact['id'].'-'.$contact['created']);
1893 $uuid = substr($hash, 0, 8). '-' . substr($hash, 8, 4) . '-' . substr($hash, 12, 4) . '-' . substr($hash, 16, 4) . '-' . substr($hash, 20, 12);
1894 return DI::baseUrl() . '/activity/' . $uuid;
1898 * Transmits a contact suggestion to a given inbox
1900 * @param integer $uid User ID
1901 * @param string $inbox Target inbox
1902 * @param integer $suggestion_id Suggestion ID
1904 * @return boolean was the transmission successful?
1905 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1907 public static function sendContactSuggestion($uid, $inbox, $suggestion_id)
1909 $owner = User::getOwnerDataById($uid);
1911 $suggestion = DI::fsuggest()->selectOneById($suggestion_id);
1913 $data = ['@context' => ActivityPub::CONTEXT,
1914 'id' => DI::baseUrl() . '/activity/' . System::createGUID(),
1915 'type' => 'Announce',
1916 'actor' => $owner['url'],
1917 'object' => $suggestion->url,
1918 'content' => $suggestion->note,
1919 'instrument' => self::getService(),
1920 'to' => [ActivityPub::PUBLIC_COLLECTION],
1923 $signed = LDSignature::sign($data, $owner);
1925 Logger::info('Deliver profile deletion for user ' . $uid . ' to ' . $inbox . ' via ActivityPub');
1926 return HTTPSignature::transmit($signed, $inbox, $uid);
1930 * Transmits a profile relocation to a given inbox
1932 * @param integer $uid User ID
1933 * @param string $inbox Target inbox
1935 * @return boolean was the transmission successful?
1936 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1938 public static function sendProfileRelocation($uid, $inbox)
1940 $owner = User::getOwnerDataById($uid);
1942 $data = ['@context' => ActivityPub::CONTEXT,
1943 'id' => DI::baseUrl() . '/activity/' . System::createGUID(),
1944 'type' => 'dfrn:relocate',
1945 'actor' => $owner['url'],
1946 'object' => $owner['url'],
1947 'published' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
1948 'instrument' => self::getService(),
1949 'to' => [ActivityPub::PUBLIC_COLLECTION],
1952 $signed = LDSignature::sign($data, $owner);
1954 Logger::info('Deliver profile relocation for user ' . $uid . ' to ' . $inbox . ' via ActivityPub');
1955 return HTTPSignature::transmit($signed, $inbox, $uid);
1959 * Transmits a profile deletion to a given inbox
1961 * @param integer $uid User ID
1962 * @param string $inbox Target inbox
1964 * @return boolean was the transmission successful?
1965 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1967 public static function sendProfileDeletion($uid, $inbox)
1969 $owner = User::getOwnerDataById($uid);
1971 if (empty($owner)) {
1972 Logger::error('No owner data found, the deletion message cannot be processed.', ['user' => $uid]);
1976 if (empty($owner['uprvkey'])) {
1977 Logger::error('No private key for owner found, the deletion message cannot be processed.', ['user' => $uid]);
1981 $data = ['@context' => ActivityPub::CONTEXT,
1982 'id' => DI::baseUrl() . '/activity/' . System::createGUID(),
1984 'actor' => $owner['url'],
1985 'object' => $owner['url'],
1986 'published' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
1987 'instrument' => self::getService(),
1988 'to' => [ActivityPub::PUBLIC_COLLECTION],
1991 $signed = LDSignature::sign($data, $owner);
1993 Logger::info('Deliver profile deletion for user ' . $uid . ' to ' . $inbox . ' via ActivityPub');
1994 return HTTPSignature::transmit($signed, $inbox, $uid);
1998 * Transmits a profile change to a given inbox
2000 * @param integer $uid User ID
2001 * @param string $inbox Target inbox
2003 * @return boolean was the transmission successful?
2004 * @throws HTTPException\InternalServerErrorException
2005 * @throws HTTPException\NotFoundException
2006 * @throws \ImagickException
2008 public static function sendProfileUpdate(int $uid, string $inbox): bool
2010 $owner = User::getOwnerDataById($uid);
2011 $profile = APContact::getByURL($owner['url']);
2013 $data = ['@context' => ActivityPub::CONTEXT,
2014 'id' => DI::baseUrl() . '/activity/' . System::createGUID(),
2016 'actor' => $owner['url'],
2017 'object' => self::getProfile($uid),
2018 'published' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
2019 'instrument' => self::getService(),
2020 'to' => [$profile['followers']],
2023 $signed = LDSignature::sign($data, $owner);
2025 Logger::info('Deliver profile update for user ' . $uid . ' to ' . $inbox . ' via ActivityPub');
2026 return HTTPSignature::transmit($signed, $inbox, $uid);
2030 * Transmits a given activity to a target
2032 * @param string $activity Type name
2033 * @param string $target Target profile
2034 * @param integer $uid User ID
2036 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2037 * @throws \ImagickException
2038 * @throws \Exception
2040 public static function sendActivity($activity, $target, $uid, $id = '')
2042 $profile = APContact::getByURL($target);
2043 if (empty($profile['inbox'])) {
2044 Logger::warning('No inbox found for target', ['target' => $target, 'profile' => $profile]);
2048 $owner = User::getOwnerDataById($uid);
2051 $id = DI::baseUrl() . '/activity/' . System::createGUID();
2054 $data = ['@context' => ActivityPub::CONTEXT,
2056 'type' => $activity,
2057 'actor' => $owner['url'],
2058 'object' => $profile['url'],
2059 'instrument' => self::getService(),
2060 'to' => [$profile['url']]];
2062 Logger::info('Sending activity ' . $activity . ' to ' . $target . ' for user ' . $uid);
2064 $signed = LDSignature::sign($data, $owner);
2065 return HTTPSignature::transmit($signed, $profile['inbox'], $uid);
2069 * Transmits a "follow object" activity to a target
2070 * This is a preparation for sending automated "follow" requests when receiving "Announce" messages
2072 * @param string $object Object URL
2073 * @param string $target Target profile
2074 * @param integer $uid User ID
2076 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2077 * @throws \ImagickException
2078 * @throws \Exception
2080 public static function sendFollowObject($object, $target, $uid = 0)
2082 $profile = APContact::getByURL($target);
2083 if (empty($profile['inbox'])) {
2084 Logger::warning('No inbox found for target', ['target' => $target, 'profile' => $profile]);
2089 // Fetch the list of administrators
2090 $admin_mail = explode(',', str_replace(' ', '', DI::config()->get('config', 'admin_email')));
2092 // We need to use some user as a sender. It doesn't care who it will send. We will use an administrator account.
2093 $condition = ['verified' => true, 'blocked' => false, 'account_removed' => false, 'account_expired' => false, 'email' => $admin_mail];
2094 $first_user = DBA::selectFirst('user', ['uid'], $condition);
2095 $uid = $first_user['uid'];
2098 $condition = ['verb' => Activity::FOLLOW, 'uid' => 0, 'parent-uri' => $object,
2099 'author-id' => Contact::getPublicIdByUserId($uid)];
2100 if (Post::exists($condition)) {
2101 Logger::info('Follow for ' . $object . ' for user ' . $uid . ' does already exist.');
2105 $owner = User::getOwnerDataById($uid);
2107 $data = ['@context' => ActivityPub::CONTEXT,
2108 'id' => DI::baseUrl() . '/activity/' . System::createGUID(),
2110 'actor' => $owner['url'],
2111 'object' => $object,
2112 'instrument' => self::getService(),
2113 'to' => [$profile['url']]];
2115 Logger::info('Sending follow ' . $object . ' to ' . $target . ' for user ' . $uid);
2117 $signed = LDSignature::sign($data, $owner);
2118 return HTTPSignature::transmit($signed, $profile['inbox'], $uid);
2122 * Transmit a message that the contact request had been accepted
2124 * @param string $target Target profile
2126 * @param integer $uid User ID
2127 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2128 * @throws \ImagickException
2130 public static function sendContactAccept($target, $id, $uid)
2132 $profile = APContact::getByURL($target);
2133 if (empty($profile['inbox'])) {
2134 Logger::warning('No inbox found for target', ['target' => $target, 'profile' => $profile]);
2138 $owner = User::getOwnerDataById($uid);
2139 $data = ['@context' => ActivityPub::CONTEXT,
2140 'id' => DI::baseUrl() . '/activity/' . System::createGUID(),
2142 'actor' => $owner['url'],
2144 'id' => (string)$id,
2146 'actor' => $profile['url'],
2147 'object' => $owner['url']
2149 'instrument' => self::getService(),
2150 'to' => [$profile['url']]];
2152 Logger::debug('Sending accept to ' . $target . ' for user ' . $uid . ' with id ' . $id);
2154 $signed = LDSignature::sign($data, $owner);
2155 HTTPSignature::transmit($signed, $profile['inbox'], $uid);
2159 * Reject a contact request or terminates the contact relation
2161 * @param string $target Target profile
2163 * @param integer $uid User ID
2164 * @return bool Operation success
2165 * @throws HTTPException\InternalServerErrorException
2166 * @throws \ImagickException
2168 public static function sendContactReject($target, $id, $uid): bool
2170 $profile = APContact::getByURL($target);
2171 if (empty($profile['inbox'])) {
2172 Logger::warning('No inbox found for target', ['target' => $target, 'profile' => $profile]);
2176 $owner = User::getOwnerDataById($uid);
2177 $data = ['@context' => ActivityPub::CONTEXT,
2178 'id' => DI::baseUrl() . '/activity/' . System::createGUID(),
2180 'actor' => $owner['url'],
2182 'id' => (string)$id,
2184 'actor' => $profile['url'],
2185 'object' => $owner['url']
2187 'instrument' => self::getService(),
2188 'to' => [$profile['url']]];
2190 Logger::debug('Sending reject to ' . $target . ' for user ' . $uid . ' with id ' . $id);
2192 $signed = LDSignature::sign($data, $owner);
2193 return HTTPSignature::transmit($signed, $profile['inbox'], $uid);
2197 * Transmits a message that we don't want to follow this contact anymore
2199 * @param string $target Target profile
2200 * @param integer $uid User ID
2201 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2202 * @throws \ImagickException
2203 * @throws \Exception
2204 * @return bool success
2206 public static function sendContactUndo($target, $cid, $uid)
2208 $profile = APContact::getByURL($target);
2209 if (empty($profile['inbox'])) {
2210 Logger::warning('No inbox found for target', ['target' => $target, 'profile' => $profile]);
2214 $object_id = self::activityIDFromContact($cid);
2215 if (empty($object_id)) {
2219 $id = DI::baseUrl() . '/activity/' . System::createGUID();
2221 $owner = User::getOwnerDataById($uid);
2222 $data = ['@context' => ActivityPub::CONTEXT,
2225 'actor' => $owner['url'],
2226 'object' => ['id' => $object_id, 'type' => 'Follow',
2227 'actor' => $owner['url'],
2228 'object' => $profile['url']],
2229 'instrument' => self::getService(),
2230 'to' => [$profile['url']]];
2232 Logger::info('Sending undo to ' . $target . ' for user ' . $uid . ' with id ' . $id);
2234 $signed = LDSignature::sign($data, $owner);
2235 return HTTPSignature::transmit($signed, $profile['inbox'], $uid);
2238 private static function prependMentions($body, int $uriid, string $authorLink)
2242 foreach (Tag::getByURIId($uriid, [Tag::IMPLICIT_MENTION]) as $tag) {
2243 $profile = Contact::getByURL($tag['url'], false, ['addr', 'contact-type', 'nick']);
2244 if (!empty($profile['addr'])
2245 && $profile['contact-type'] != Contact::TYPE_COMMUNITY
2246 && !strstr($body, $profile['addr'])
2247 && !strstr($body, $tag['url'])
2248 && $tag['url'] !== $authorLink
2250 $mentions[] = '@[url=' . $tag['url'] . ']' . $profile['nick'] . '[/url]';
2254 $mentions[] = $body;
2256 return implode(' ', $mentions);