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\LDSignature;
48 use Friendica\Util\Map;
49 use Friendica\Util\Network;
50 use Friendica\Util\Strings;
51 use Friendica\Util\XML;
54 * ActivityPub Transmitter Protocol class
61 const CACHEKEY_FEATURED = 'transmitter:getFeatured:';
62 const CACHEKEY_CONTACTS = 'transmitter:getContacts:';
63 const CACHEKEY_OUTBOX = 'transmitter:getOutbox:';
64 const CACHEKEY_PROFILE = 'transmitter:getProfile:';
67 * Add relay servers to the list of inboxes
69 * @param array $inboxes
70 * @return array inboxes with added relay servers
72 public static function addRelayServerInboxes(array $inboxes = [])
74 foreach (Relay::getList(['inbox']) as $contact) {
75 $inboxes[$contact['inbox']] = $contact['inbox'];
82 * Add relay servers to the list of inboxes
84 * @param array $inboxes
85 * @return array inboxes with added relay servers
87 public static function addRelayServerInboxesForItem(int $item_id, array $inboxes = [])
89 $item = Post::selectFirst(['uid'], ['id' => $item_id]);
94 $relays = Relay::getDirectRelayList($item_id);
99 foreach ($relays as $relay) {
100 $contact = Contact::getByURLForUser($relay['url'], $item['uid'], false, ['id']);
101 $inboxes[$relay['batch']][] = $contact['id'] ?? 0;
107 * Subscribe to a relay
109 * @param string $url Subscribe actor url
110 * @return bool success
112 public static function sendRelayFollow(string $url)
114 $contact = Contact::getByURL($url);
115 if (empty($contact)) {
119 $activity_id = ActivityPub\Transmitter::activityIDFromContact($contact['id']);
120 $success = ActivityPub\Transmitter::sendActivity('Follow', $url, 0, $activity_id);
122 Contact::update(['rel' => Contact::FRIEND], ['id' => $contact['id']]);
129 * Unsubscribe from a relay
131 * @param string $url Subscribe actor url
132 * @param bool $force Set the relay status as non follower even if unsubscribe hadn't worked
133 * @return bool success
135 public static function sendRelayUndoFollow(string $url, bool $force = false)
137 $contact = Contact::getByURL($url);
138 if (empty($contact)) {
142 $success = self::sendContactUndo($url, $contact['id'], 0);
143 if ($success || $force) {
144 Contact::update(['rel' => Contact::NOTHING], ['id' => $contact['id']]);
151 * Collects a list of contacts of the given owner
153 * @param array $owner Owner array
154 * @param array $rel The relevant value(s) contact.rel should match
155 * @param string $module The name of the relevant AP endpoint module (followers|following)
156 * @param integer $page Page number
157 * @param string $requester URL of the requester
158 * @param boolean $nocache Wether to bypass caching
160 * @return array of owners
163 public static function getContacts(array $owner, array $rel, string $module, int $page = null, string $requester = null, $nocache = false)
166 $cachekey = self::CACHEKEY_CONTACTS . $module . ':'. $owner['uid'];
167 $result = DI::cache()->get($cachekey);
168 if (!$nocache && !is_null($result)) {
175 'uid' => $owner['uid'],
184 $condition = DBA::mergeConditions($parameters, ["`url` IN (SELECT `url` FROM `apcontact`)"]);
186 $total = DBA::count('contact', $condition);
188 $modulePath = '/' . $module . '/';
190 $data = ['@context' => ActivityPub::CONTEXT];
191 $data['id'] = DI::baseUrl() . $modulePath . $owner['nickname'];
192 $data['type'] = 'OrderedCollection';
193 $data['totalItems'] = $total;
196 $data['id'] .= '?' . http_build_query(['page' => $page]);
199 // When we hide our friends we will only show the pure number but don't allow more.
200 $show_contacts = empty($owner['hide-friends']);
202 // Allow fetching the contact list when the requester is part of the list.
203 if (($owner['page-flags'] == User::PAGE_FLAGS_PRVGROUP) && !empty($requester)) {
204 $show_contacts = DBA::exists('contact', ['nurl' => Strings::normaliseLink($requester), 'uid' => $owner['uid'], 'blocked' => false]);
207 if (!$show_contacts) {
208 if (!empty($cachekey)) {
209 DI::cache()->set($cachekey, $data, Duration::DAY);
216 $data['first'] = DI::baseUrl() . $modulePath . $owner['nickname'] . '?page=1';
218 $data['type'] = 'OrderedCollectionPage';
221 $contacts = DBA::select('contact', ['url'], $condition, ['limit' => [($page - 1) * 100, 100]]);
222 while ($contact = DBA::fetch($contacts)) {
223 $list[] = $contact['url'];
225 DBA::close($contacts);
227 if (count($list) == 100) {
228 $data['next'] = DI::baseUrl() . $modulePath . $owner['nickname'] . '?page=' . ($page + 1);
231 $data['partOf'] = DI::baseUrl() . $modulePath . $owner['nickname'];
233 $data['orderedItems'] = $list;
236 if (!empty($cachekey)) {
237 DI::cache()->set($cachekey, $data, Duration::DAY);
244 * Public posts for the given owner
246 * @param array $owner Owner array
247 * @param integer $page Page number
248 * @param string $requester URL of requesting account
249 * @param boolean $nocache Wether to bypass caching
251 * @return array of posts
252 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
253 * @throws \ImagickException
255 public static function getOutbox(array $owner, int $page = null, string $requester = '', $nocache = false)
258 $cachekey = self::CACHEKEY_OUTBOX . $owner['uid'];
259 $result = DI::cache()->get($cachekey);
260 if (!$nocache && !is_null($result)) {
265 $condition = ['private' => [Item::PUBLIC, Item::UNLISTED]];
267 if (!empty($requester)) {
268 $requester_id = Contact::getIdForURL($requester, $owner['uid']);
269 if (!empty($requester_id)) {
270 $permissionSets = DI::permissionSet()->selectByContactId($requester_id, $owner['uid']);
271 if (!empty($permissionSets)) {
272 $condition = ['psid' => array_merge($permissionSets->column('id'),
273 [DI::permissionSet()->selectPublicForUser($owner['uid'])])];
278 $condition = array_merge($condition,
279 ['uid' => $owner['uid'],
280 'author-id' => Contact::getIdForURL($owner['url'], 0, false),
281 'gravity' => [GRAVITY_PARENT, GRAVITY_COMMENT],
282 'network' => Protocol::FEDERATED,
283 'parent-network' => Protocol::FEDERATED,
288 $count = Post::count($condition);
290 $data = ['@context' => ActivityPub::CONTEXT];
291 $data['id'] = DI::baseUrl() . '/outbox/' . $owner['nickname'];
292 $data['type'] = 'OrderedCollection';
293 $data['totalItems'] = $count;
296 $data['id'] .= '?' . http_build_query(['page' => $page]);
300 $data['first'] = DI::baseUrl() . '/outbox/' . $owner['nickname'] . '?page=1';
302 $data['type'] = 'OrderedCollectionPage';
305 $items = Post::select(['id'], $condition, ['limit' => [($page - 1) * 20, 20], 'order' => ['created' => true]]);
306 while ($item = Post::fetch($items)) {
307 $activity = self::createActivityFromItem($item['id'], true);
308 $activity['type'] = $activity['type'] == 'Update' ? 'Create' : $activity['type'];
310 // Only list "Create" activity objects here, no reshares
311 if (!empty($activity['object']) && ($activity['type'] == 'Create')) {
312 $list[] = $activity['object'];
317 if (count($list) == 20) {
318 $data['next'] = DI::baseUrl() . '/outbox/' . $owner['nickname'] . '?page=' . ($page + 1);
321 $data['partOf'] = DI::baseUrl() . '/outbox/' . $owner['nickname'];
323 $data['orderedItems'] = $list;
326 if (!empty($cachekey)) {
327 DI::cache()->set($cachekey, $data, Duration::DAY);
334 * Public posts for the given owner
336 * @param array $owner Owner array
337 * @param integer $page Page number
338 * @param boolean $nocache Wether to bypass caching
340 * @return array of posts
341 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
342 * @throws \ImagickException
344 public static function getFeatured(array $owner, int $page = null, $nocache = false)
347 $cachekey = self::CACHEKEY_FEATURED . $owner['uid'];
348 $result = DI::cache()->get($cachekey);
349 if (!$nocache && !is_null($result)) {
354 $owner_cid = Contact::getIdForURL($owner['url'], 0, false);
356 $condition = ["`uri-id` IN (SELECT `uri-id` FROM `collection-view` WHERE `cid` = ? AND `type` = ?)",
357 $owner_cid, Post\Collection::FEATURED];
359 $condition = DBA::mergeConditions($condition,
360 ['uid' => $owner['uid'],
361 'author-id' => $owner_cid,
362 'private' => [Item::PUBLIC, Item::UNLISTED],
363 'gravity' => [GRAVITY_PARENT, GRAVITY_COMMENT],
364 'network' => Protocol::FEDERATED,
365 'parent-network' => Protocol::FEDERATED,
370 $count = Post::count($condition);
372 $data = ['@context' => ActivityPub::CONTEXT];
373 $data['id'] = DI::baseUrl() . '/featured/' . $owner['nickname'];
374 $data['type'] = 'OrderedCollection';
375 $data['totalItems'] = $count;
378 $data['id'] .= '?' . http_build_query(['page' => $page]);
382 $items = Post::select(['id'], $condition, ['limit' => 20, 'order' => ['created' => true]]);
384 $data['type'] = 'OrderedCollectionPage';
385 $items = Post::select(['id'], $condition, ['limit' => [($page - 1) * 20, 20], 'order' => ['created' => true]]);
389 while ($item = Post::fetch($items)) {
390 $activity = self::createActivityFromItem($item['id'], true);
391 $activity['type'] = $activity['type'] == 'Update' ? 'Create' : $activity['type'];
393 // Only list "Create" activity objects here, no reshares
394 if (!empty($activity['object']) && ($activity['type'] == 'Create')) {
395 $list[] = $activity['object'];
400 if (count($list) == 20) {
401 $data['next'] = DI::baseUrl() . '/featured/' . $owner['nickname'] . '?page=' . ($page + 1);
405 $data['partOf'] = DI::baseUrl() . '/featured/' . $owner['nickname'];
408 $data['orderedItems'] = $list;
410 if (!empty($cachekey)) {
411 DI::cache()->set($cachekey, $data, Duration::DAY);
418 * Return the service array containing information the used software and it's url
420 * @return array with service data
422 private static function getService()
424 return ['type' => 'Service',
425 'name' => FRIENDICA_PLATFORM . " '" . FRIENDICA_CODENAME . "' " . FRIENDICA_VERSION . '-' . DB_UPDATE_VERSION,
426 'url' => DI::baseUrl()->get()];
430 * Return the ActivityPub profile of the given user
432 * @param int $uid User ID
433 * @param boolean $nocache Wether to bypass caching
434 * @return array with profile data
435 * @throws HTTPException\NotFoundException
436 * @throws HTTPException\InternalServerErrorException
438 public static function getProfile(int $uid, $nocache = false): array
440 $cachekey = self::CACHEKEY_PROFILE . $uid;
441 $result = DI::cache()->get($cachekey);
442 if (!$nocache && !is_null($result)) {
446 $owner = User::getOwnerDataById($uid);
447 if (!isset($owner['id'])) {
448 DI::logger()->error('Unable to find owner data for uid', ['uid' => $uid, 'callstack' => System::callstack(20)]);
449 throw new HTTPException\NotFoundException('User not found.');
452 $data = ['@context' => ActivityPub::CONTEXT];
453 $data['id'] = $owner['url'];
455 if (!empty($owner['guid'])) {
456 $data['diaspora:guid'] = $owner['guid'];
459 $data['type'] = ActivityPub::ACCOUNT_TYPES[$owner['account-type']];
462 $data['following'] = DI::baseUrl() . '/following/' . $owner['nick'];
463 $data['followers'] = DI::baseUrl() . '/followers/' . $owner['nick'];
464 $data['inbox'] = DI::baseUrl() . '/inbox/' . $owner['nick'];
465 $data['outbox'] = DI::baseUrl() . '/outbox/' . $owner['nick'];
466 $data['featured'] = DI::baseUrl() . '/featured/' . $owner['nick'];
468 $data['inbox'] = DI::baseUrl() . '/friendica/inbox';
471 $data['preferredUsername'] = $owner['nick'];
472 $data['name'] = $owner['name'];
474 if (!empty($owner['country-name'] . $owner['region'] . $owner['locality'])) {
475 $data['vcard:hasAddress'] = ['@type' => 'vcard:Home', 'vcard:country-name' => $owner['country-name'],
476 'vcard:region' => $owner['region'], 'vcard:locality' => $owner['locality']];
479 if (!empty($owner['about'])) {
480 $data['summary'] = BBCode::convertForUriId($owner['uri-id'] ?? 0, $owner['about'], BBCode::EXTERNAL);
483 if (!empty($owner['xmpp']) || !empty($owner['matrix'])) {
484 $data['vcard:hasInstantMessage'] = [];
486 if (!empty($owner['xmpp'])) {
487 $data['vcard:hasInstantMessage'][] = 'xmpp:' . $owner['xmpp'];
489 if (!empty($owner['matrix'])) {
490 $data['vcard:hasInstantMessage'][] = 'matrix:' . $owner['matrix'];
494 $data['url'] = $owner['url'];
495 $data['manuallyApprovesFollowers'] = in_array($owner['page-flags'], [User::PAGE_FLAGS_NORMAL, User::PAGE_FLAGS_PRVGROUP]);
496 $data['discoverable'] = (bool)$owner['net-publish'];
497 $data['publicKey'] = ['id' => $owner['url'] . '#main-key',
498 'owner' => $owner['url'],
499 'publicKeyPem' => $owner['pubkey']];
500 $data['endpoints'] = ['sharedInbox' => DI::baseUrl() . '/inbox'];
501 $data['icon'] = ['type' => 'Image', 'url' => User::getAvatarUrl($owner)];
503 $resourceid = Photo::ridFromURI($owner['photo']);
504 if (!empty($resourceid)) {
505 $photo = Photo::selectFirst(['type'], ["resource-id" => $resourceid]);
506 if (!empty($photo['type'])) {
507 $data['icon']['mediaType'] = $photo['type'];
511 if (!empty($owner['header'])) {
512 $data['image'] = ['type' => 'Image', 'url' => Contact::getHeaderUrlForId($owner['id'], '', $owner['updated'])];
514 $resourceid = Photo::ridFromURI($owner['header']);
515 if (!empty($resourceid)) {
516 $photo = Photo::selectFirst(['type'], ["resource-id" => $resourceid]);
517 if (!empty($photo['type'])) {
518 $data['image']['mediaType'] = $photo['type'];
525 foreach (DI::profileField()->selectByContactId(0, $uid) as $profile_field) {
527 'type' => 'PropertyValue',
528 'name' => $profile_field->label,
529 'value' => BBCode::convertForUriId($owner['uri-id'], $profile_field->value)
533 if (!empty($custom_fields)) {
534 $data['attachment'] = $custom_fields;
537 $data['generator'] = self::getService();
539 DI::cache()->set($cachekey, $data, Duration::DAY);
541 // tags: https://kitty.town/@inmysocks/100656097926961126.json
546 * @param string $username
548 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
550 public static function getDeletedUser($username)
553 '@context' => ActivityPub::CONTEXT,
554 'id' => DI::baseUrl() . '/profile/' . $username,
555 'type' => 'Tombstone',
556 'published' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
557 'updated' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
558 'deleted' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
563 * Returns an array with permissions of the thread parent of the given item array
566 * @param bool $is_forum_thread
568 * @return array with permissions
569 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
570 * @throws \ImagickException
572 private static function fetchPermissionBlockFromThreadParent(array $item, bool $is_forum_thread)
574 if (empty($item['thr-parent-id'])) {
578 $parent = Post::selectFirstPost(['author-link'], ['uri-id' => $item['thr-parent-id']]);
579 if (empty($parent)) {
584 'to' => [$parent['author-link']],
590 $parent_profile = APContact::getByURL($parent['author-link']);
592 $item_profile = APContact::getByURL($item['author-link']);
593 $exclude[] = $item['author-link'];
595 if ($item['gravity'] == GRAVITY_PARENT) {
596 $exclude[] = $item['owner-link'];
599 $type = [Tag::TO => 'to', Tag::CC => 'cc', Tag::BTO => 'bto', Tag::BCC => 'bcc'];
600 foreach (Tag::getByURIId($item['thr-parent-id'], [Tag::TO, Tag::CC, Tag::BTO, Tag::BCC]) as $receiver) {
601 if (!empty($parent_profile['followers']) && $receiver['url'] == $parent_profile['followers'] && !empty($item_profile['followers'])) {
602 if (!$is_forum_thread) {
603 $permissions[$type[$receiver['type']]][] = $item_profile['followers'];
605 } elseif (!in_array($receiver['url'], $exclude)) {
606 $permissions[$type[$receiver['type']]][] = $receiver['url'];
614 * Check if the given item id is from ActivityPub
616 * @param integer $item_id
617 * @return boolean "true" if the post is from ActivityPub
619 private static function isAPPost(int $item_id)
621 if (empty($item_id)) {
625 return Post::exists(['id' => $item_id, 'network' => Protocol::ACTIVITYPUB]);
629 * Creates an array of permissions from an item thread
631 * @param array $item Item array
632 * @param boolean $blindcopy addressing via "bcc" or "cc"?
633 * @param integer $last_id Last item id for adding receivers
635 * @return array with permission data
636 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
637 * @throws \ImagickException
639 private static function createPermissionBlockForItem($item, $blindcopy, $last_id = 0)
642 $last_id = $item['id'];
649 // Check if we should always deliver our stuff via BCC
650 if (!empty($item['uid'])) {
651 $owner = User::getOwnerDataById($item['uid']);
652 if (!empty($owner)) {
653 $always_bcc = $owner['hide-friends'];
654 $is_forum = ($owner['account-type'] == User::ACCOUNT_TYPE_COMMUNITY) && $owner['manually-approve'];
656 $profile = APContact::getByURL($owner['url'], false);
657 $follower = $profile['followers'] ?? '';
661 if (DI::config()->get('system', 'ap_always_bcc')) {
665 $parent = Post::selectFirst(['causer-link', 'post-reason'], ['id' => $item['parent']]);
666 if (($parent['post-reason'] == Item::PR_ANNOUNCEMENT) && !empty($parent['causer-link'])) {
667 $profile = APContact::getByURL($parent['causer-link'], false);
668 $is_forum_thread = isset($profile['type']) && $profile['type'] == 'Group';
670 $is_forum_thread = false;
673 if (self::isAnnounce($item) || DI::config()->get('debug', 'total_ap_delivery') || self::isAPPost($last_id)) {
674 // Will be activated in a later step
675 $networks = Protocol::FEDERATED;
677 // For now only send to these contacts:
678 $networks = [Protocol::ACTIVITYPUB, Protocol::OSTATUS];
681 $data = ['to' => [], 'cc' => [], 'bcc' => []];
683 if ($item['gravity'] == GRAVITY_PARENT) {
684 $actor_profile = APContact::getByURL($item['owner-link']);
686 $actor_profile = APContact::getByURL($item['author-link']);
691 $terms = Tag::getByURIId($item['uri-id'], [Tag::MENTION, Tag::IMPLICIT_MENTION, Tag::EXCLUSIVE_MENTION]);
693 if ($item['private'] != Item::PRIVATE) {
694 // Directly mention the original author upon a quoted reshare.
695 // Else just ensure that the original author receives the reshare.
696 $announce = self::getAnnounceArray($item);
697 if (!empty($announce['comment'])) {
698 $data['to'][] = $announce['actor']['url'];
699 } elseif (!empty($announce)) {
700 $data['cc'][] = $announce['actor']['url'];
703 $data = array_merge($data, self::fetchPermissionBlockFromThreadParent($item, $is_forum_thread));
705 // Check if the item is completely public or unlisted
706 if ($item['private'] == Item::PUBLIC) {
707 $data['to'][] = ActivityPub::PUBLIC_COLLECTION;
709 $data['cc'][] = ActivityPub::PUBLIC_COLLECTION;
712 foreach ($terms as $term) {
713 $profile = APContact::getByURL($term['url'], false);
714 if (!empty($profile)) {
715 if ($term['type'] == Tag::EXCLUSIVE_MENTION) {
717 if (!empty($profile['followers']) && ($profile['type'] == 'Group')) {
718 $data['cc'][] = $profile['followers'];
721 $data['to'][] = $profile['url'];
725 $receiver_list = Item::enumeratePermissions($item, true);
727 foreach ($terms as $term) {
728 $cid = Contact::getIdForURL($term['url'], $item['uid']);
729 if (!empty($cid) && in_array($cid, $receiver_list)) {
730 $contact = DBA::selectFirst('contact', ['url', 'network', 'protocol', 'gsid'], ['id' => $cid, 'network' => Protocol::FEDERATED]);
731 if (!DBA::isResult($contact) || !self::isAPContact($contact, $networks)) {
735 $profile = APContact::getByURL($term['url'], false);
736 if (!empty($profile)) {
737 if ($term['type'] == Tag::EXCLUSIVE_MENTION) {
739 if (!empty($profile['followers']) && ($profile['type'] == 'Group')) {
740 $data['cc'][] = $profile['followers'];
743 $data['to'][] = $profile['url'];
748 if ($is_forum && !$exclusive && !empty($follower)) {
749 $data['cc'][] = $follower;
750 } elseif (!$exclusive) {
751 foreach ($receiver_list as $receiver) {
752 $contact = DBA::selectFirst('contact', ['url', 'hidden', 'network', 'protocol', 'gsid'], ['id' => $receiver, 'network' => Protocol::FEDERATED]);
753 if (!DBA::isResult($contact) || !self::isAPContact($contact, $networks)) {
757 if (!empty($profile = APContact::getByURL($contact['url'], false))) {
758 if ($contact['hidden'] || $always_bcc) {
759 $data['bcc'][] = $profile['url'];
761 $data['cc'][] = $profile['url'];
768 if (!empty($item['parent'])) {
769 $parents = Post::select(['id', 'author-link', 'owner-link', 'gravity', 'uri'], ['parent' => $item['parent']], ['order' => ['id']]);
770 while ($parent = Post::fetch($parents)) {
771 if ($parent['gravity'] == GRAVITY_PARENT) {
772 $profile = APContact::getByURL($parent['owner-link'], false);
773 if (!empty($profile)) {
774 if ($item['gravity'] != GRAVITY_PARENT) {
775 // Comments to forums are directed to the forum
776 // But comments to forums aren't directed to the followers collection
777 // This rule is only valid when the actor isn't the forum.
778 // The forum needs to transmit their content to their followers.
779 if (($profile['type'] == 'Group') && ($profile['url'] != ($actor_profile['url'] ?? ''))) {
780 $data['to'][] = $profile['url'];
782 $data['cc'][] = $profile['url'];
783 if (($item['private'] != Item::PRIVATE) && !empty($actor_profile['followers'])&& !$is_forum_thread) {
784 $data['cc'][] = $actor_profile['followers'];
787 } elseif (!$exclusive && !$is_forum_thread) {
788 // Public thread parent post always are directed to the followers.
789 if ($item['private'] != Item::PRIVATE) {
790 $data['cc'][] = $actor_profile['followers'];
796 // Don't include data from future posts
797 if ($parent['id'] >= $last_id) {
801 $profile = APContact::getByURL($parent['author-link'], false);
802 if (!empty($profile)) {
803 if (($profile['type'] == 'Group') || ($parent['uri'] == $item['thr-parent'])) {
804 $data['to'][] = $profile['url'];
806 $data['cc'][] = $profile['url'];
810 DBA::close($parents);
813 $data['to'] = array_unique($data['to']);
814 $data['cc'] = array_unique($data['cc']);
815 $data['bcc'] = array_unique($data['bcc']);
817 if (($key = array_search($item['author-link'], $data['to'])) !== false) {
818 unset($data['to'][$key]);
821 if (($key = array_search($item['author-link'], $data['cc'])) !== false) {
822 unset($data['cc'][$key]);
825 if (($key = array_search($item['author-link'], $data['bcc'])) !== false) {
826 unset($data['bcc'][$key]);
829 foreach ($data['to'] as $to) {
830 if (($key = array_search($to, $data['cc'])) !== false) {
831 unset($data['cc'][$key]);
834 if (($key = array_search($to, $data['bcc'])) !== false) {
835 unset($data['bcc'][$key]);
839 foreach ($data['cc'] as $cc) {
840 if (($key = array_search($cc, $data['bcc'])) !== false) {
841 unset($data['bcc'][$key]);
845 $receivers = ['to' => array_values($data['to']), 'cc' => array_values($data['cc']), 'bcc' => array_values($data['bcc'])];
848 unset($receivers['bcc']);
851 foreach (['to' => Tag::TO, 'cc' => Tag::CC, 'bcc' => Tag::BCC] as $element => $type) {
852 if (!empty($receivers[$element])) {
853 foreach ($receivers[$element] as $receiver) {
854 if ($receiver == ActivityPub::PUBLIC_COLLECTION) {
855 $name = Receiver::PUBLIC_COLLECTION;
857 $name = trim(parse_url($receiver, PHP_URL_PATH), '/');
859 Tag::store($item['uri-id'], $type, $name, $receiver);
868 * Check if an inbox is archived
870 * @param string $url Inbox url
872 * @return boolean "true" if inbox is archived
874 public static function archivedInbox($url)
876 return DBA::exists('inbox-status', ['url' => $url, 'archive' => true]);
880 * Check if a given contact should be delivered via AP
882 * @param array $contact
883 * @param array $networks
887 private static function isAPContact(array $contact, array $networks)
889 if (in_array($contact['network'], $networks) || ($contact['protocol'] == Protocol::ACTIVITYPUB)) {
893 return GServer::getProtocol($contact['gsid'] ?? 0) == Post\DeliveryData::ACTIVITYPUB;
897 * Fetches a list of inboxes of followers of a given user
899 * @param integer $uid User ID
900 * @param boolean $personal fetch personal inboxes
901 * @param boolean $all_ap Retrieve all AP enabled inboxes
903 * @return array of follower inboxes
904 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
905 * @throws \ImagickException
907 public static function fetchTargetInboxesforUser($uid, $personal = false, bool $all_ap = false)
913 if (!empty($item['uid'])) {
914 $profile = User::getOwnerDataById($item['uid']);
915 if (!empty($profile)) {
916 $isforum = $profile['account-type'] == User::ACCOUNT_TYPE_COMMUNITY;
920 if (DI::config()->get('debug', 'total_ap_delivery') || $all_ap) {
921 // Will be activated in a later step
922 $networks = Protocol::FEDERATED;
924 // For now only send to these contacts:
925 $networks = [Protocol::ACTIVITYPUB, Protocol::OSTATUS];
928 $condition = ['uid' => $uid, 'archive' => false, 'pending' => false, 'blocked' => false, 'network' => Protocol::FEDERATED];
931 $condition['rel'] = [Contact::FOLLOWER, Contact::FRIEND];
934 $contacts = DBA::select('contact', ['id', 'url', 'network', 'protocol', 'gsid'], $condition);
935 while ($contact = DBA::fetch($contacts)) {
936 if (!self::isAPContact($contact, $networks)) {
940 if ($isforum && ($contact['network'] == Protocol::DFRN)) {
944 if (Network::isUrlBlocked($contact['url'])) {
948 $profile = APContact::getByURL($contact['url'], false);
949 if (!empty($profile)) {
950 if (empty($profile['sharedinbox']) || $personal || Contact::isLocal($contact['url'])) {
951 $target = $profile['inbox'];
953 $target = $profile['sharedinbox'];
955 if (!self::archivedInbox($target)) {
956 $inboxes[$target][] = $contact['id'];
960 DBA::close($contacts);
966 * Fetches an array of inboxes for the given item and user
968 * @param array $item Item array
969 * @param integer $uid User ID
970 * @param boolean $personal fetch personal inboxes
971 * @param integer $last_id Last item id for adding receivers
972 * @return array with inboxes
973 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
974 * @throws \ImagickException
976 public static function fetchTargetInboxes($item, $uid, $personal = false, $last_id = 0)
978 $permissions = self::createPermissionBlockForItem($item, true, $last_id);
979 if (empty($permissions)) {
985 if ($item['gravity'] == GRAVITY_ACTIVITY) {
986 $item_profile = APContact::getByURL($item['author-link'], false);
988 $item_profile = APContact::getByURL($item['owner-link'], false);
991 if (empty($item_profile)) {
995 $profile_uid = User::getIdForURL($item_profile['url']);
997 foreach (['to', 'cc', 'bto', 'bcc'] as $element) {
998 if (empty($permissions[$element])) {
1002 $blindcopy = in_array($element, ['bto', 'bcc']);
1004 foreach ($permissions[$element] as $receiver) {
1005 if (empty($receiver) || Network::isUrlBlocked($receiver)) {
1009 if ($item_profile && ($receiver == $item_profile['followers']) && ($uid == $profile_uid)) {
1010 $inboxes = array_merge($inboxes, self::fetchTargetInboxesforUser($uid, $personal, self::isAPPost($last_id)));
1012 $profile = APContact::getByURL($receiver, false);
1013 if (!empty($profile)) {
1014 $contact = Contact::getByURLForUser($receiver, $uid, false, ['id']);
1016 if (empty($profile['sharedinbox']) || $personal || $blindcopy || Contact::isLocal($receiver)) {
1017 $target = $profile['inbox'];
1019 $target = $profile['sharedinbox'];
1021 if (!self::archivedInbox($target)) {
1022 $inboxes[$target][] = $contact['id'] ?? 0;
1033 * Creates an array in the structure of the item table for a given mail id
1035 * @param integer $mail_id
1038 * @throws \Exception
1040 public static function ItemArrayFromMail($mail_id, $use_title = false)
1042 $mail = DBA::selectFirst('mail', [], ['id' => $mail_id]);
1043 if (!DBA::isResult($mail)) {
1047 $reply = DBA::selectFirst('mail', ['uri', 'uri-id', 'from-url'], ['parent-uri' => $mail['parent-uri'], 'reply' => false]);
1048 if (!DBA::isResult($reply)) {
1052 // Making the post more compatible for Mastodon by:
1053 // - Making it a note and not an article (no title)
1054 // - Moving the title into the "summary" field that is used as a "content warning"
1057 $mail['body'] = '[abstract]' . $mail['title'] . "[/abstract]\n" . $mail['body'];
1058 $mail['title'] = '';
1061 $mail['content-warning'] = '';
1062 $mail['author-link'] = $mail['owner-link'] = $mail['from-url'];
1063 $mail['owner-id'] = $mail['author-id'];
1064 $mail['allow_cid'] = '<'.$mail['contact-id'].'>';
1065 $mail['allow_gid'] = '';
1066 $mail['deny_cid'] = '';
1067 $mail['deny_gid'] = '';
1068 $mail['private'] = Item::PRIVATE;
1069 $mail['deleted'] = false;
1070 $mail['edited'] = $mail['created'];
1071 $mail['plink'] = DI::baseUrl() . '/message/' . $mail['id'];
1072 $mail['parent-uri'] = $reply['uri'];
1073 $mail['parent-uri-id'] = $reply['uri-id'];
1074 $mail['parent-author-id'] = Contact::getIdForURL($reply['from-url'], 0, false);
1075 $mail['gravity'] = ($mail['reply'] ? GRAVITY_COMMENT: GRAVITY_PARENT);
1076 $mail['event-type'] = '';
1077 $mail['language'] = '';
1078 $mail['parent'] = 0;
1084 * Creates an activity array for a given mail id
1086 * @param integer $mail_id
1087 * @param boolean $object_mode Is the activity item is used inside another object?
1089 * @return array of activity
1090 * @throws \Exception
1092 public static function createActivityFromMail($mail_id, $object_mode = false)
1094 $mail = self::ItemArrayFromMail($mail_id);
1098 $object = self::createNote($mail);
1100 if (!$object_mode) {
1101 $data = ['@context' => ActivityPub::CONTEXT];
1106 $data['id'] = $mail['uri'] . '/Create';
1107 $data['type'] = 'Create';
1108 $data['actor'] = $mail['author-link'];
1109 $data['published'] = DateTimeFormat::utc($mail['created'] . '+00:00', DateTimeFormat::ATOM);
1110 $data['instrument'] = self::getService();
1111 $data = array_merge($data, self::createPermissionBlockForItem($mail, true));
1113 if (empty($data['to']) && !empty($data['cc'])) {
1114 $data['to'] = $data['cc'];
1117 if (empty($data['to']) && !empty($data['bcc'])) {
1118 $data['to'] = $data['bcc'];
1122 unset($data['bcc']);
1124 $object['to'] = $data['to'];
1125 $object['tag'] = [['type' => 'Mention', 'href' => $object['to'][0], 'name' => '']];
1127 unset($object['cc']);
1128 unset($object['bcc']);
1130 $data['directMessage'] = true;
1132 $data['object'] = $object;
1134 $owner = User::getOwnerDataById($mail['uid']);
1136 if (!$object_mode && !empty($owner)) {
1137 return LDSignature::sign($data, $owner);
1144 * Returns the activity type of a given item
1146 * @param array $item
1148 * @return string with activity type
1149 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1150 * @throws \ImagickException
1152 private static function getTypeOfItem($item)
1156 // Only check for a reshare, if it is a real reshare and no quoted reshare
1157 if (strpos($item['body'], "[share") === 0) {
1158 $announce = self::getAnnounceArray($item);
1159 $reshared = !empty($announce);
1164 } elseif ($item['verb'] == Activity::POST) {
1165 if ($item['created'] == $item['edited']) {
1170 } elseif ($item['verb'] == Activity::LIKE) {
1172 } elseif ($item['verb'] == Activity::DISLIKE) {
1174 } elseif ($item['verb'] == Activity::ATTEND) {
1176 } elseif ($item['verb'] == Activity::ATTENDNO) {
1178 } elseif ($item['verb'] == Activity::ATTENDMAYBE) {
1179 $type = 'TentativeAccept';
1180 } elseif ($item['verb'] == Activity::FOLLOW) {
1182 } elseif ($item['verb'] == Activity::TAG) {
1184 } elseif ($item['verb'] == Activity::ANNOUNCE) {
1194 * Creates the activity or fetches it from the cache
1196 * @param integer $item_id
1197 * @param boolean $force Force new cache entry
1199 * @return array with the activity
1200 * @throws \Exception
1202 public static function createCachedActivityFromItem($item_id, $force = false)
1204 $cachekey = 'APDelivery:createActivity:' . $item_id;
1207 $data = DI::cache()->get($cachekey);
1208 if (!is_null($data)) {
1213 $data = self::createActivityFromItem($item_id);
1215 DI::cache()->set($cachekey, $data, Duration::QUARTER_HOUR);
1220 * Creates an activity array for a given item id
1222 * @param integer $item_id
1223 * @param boolean $object_mode Is the activity item is used inside another object?
1225 * @return false|array
1226 * @throws \Exception
1228 public static function createActivityFromItem(int $item_id, bool $object_mode = false)
1230 Logger::info('Fetching activity', ['item' => $item_id]);
1231 $item = Post::selectFirst(Item::DELIVER_FIELDLIST, ['id' => $item_id, 'parent-network' => Protocol::NATIVE_SUPPORT]);
1232 if (!DBA::isResult($item)) {
1236 if (empty($item['uri-id'])) {
1237 Logger::warning('Item without uri-id', ['item' => $item]);
1241 if (!$item['deleted']) {
1242 $condition = ['item-uri' => $item['uri'], 'protocol' => Conversation::PARCEL_ACTIVITYPUB];
1243 $conversation = DBA::selectFirst('conversation', ['source'], $condition);
1244 if (!$item['origin'] && DBA::isResult($conversation)) {
1245 $data = json_decode($conversation['source'], true);
1246 if (!empty($data['type'])) {
1247 if (in_array($data['type'], ['Create', 'Update'])) {
1249 unset($data['@context']);
1250 unset($data['signature']);
1252 Logger::info('Return stored conversation', ['item' => $item_id]);
1254 } elseif (in_array('as:' . $data['type'], Receiver::CONTENT_TYPES)) {
1255 if (!empty($data['@context'])) {
1256 $context = $data['@context'];
1257 unset($data['@context']);
1259 unset($data['actor']);
1266 $type = self::getTypeOfItem($item);
1268 if (!$object_mode) {
1269 $data = ['@context' => $context ?? ActivityPub::CONTEXT];
1271 if ($item['deleted'] && ($item['gravity'] == GRAVITY_ACTIVITY)) {
1273 } elseif ($item['deleted']) {
1280 if ($type == 'Delete') {
1281 $data['id'] = Item::newURI($item['uid'], $item['guid']) . '/' . $type;;
1282 } elseif (($item['gravity'] == GRAVITY_ACTIVITY) && ($type != 'Undo')) {
1283 $data['id'] = $item['uri'];
1285 $data['id'] = $item['uri'] . '/' . $type;
1288 $data['type'] = $type;
1290 if (($type != 'Announce') || ($item['gravity'] != GRAVITY_PARENT)) {
1291 $data['actor'] = $item['author-link'];
1293 $data['actor'] = $item['owner-link'];
1296 $data['published'] = DateTimeFormat::utc($item['created'] . '+00:00', DateTimeFormat::ATOM);
1298 $data['instrument'] = self::getService();
1300 $data = array_merge($data, self::createPermissionBlockForItem($item, false));
1302 if (in_array($data['type'], ['Create', 'Update', 'Delete'])) {
1303 $data['object'] = $object ?? self::createNote($item);
1304 $data['published'] = DateTimeFormat::utcNow(DateTimeFormat::ATOM);
1305 } elseif ($data['type'] == 'Add') {
1306 $data = self::createAddTag($item, $data);
1307 } elseif ($data['type'] == 'Announce') {
1308 if ($item['verb'] == ACTIVITY::ANNOUNCE) {
1309 $data['object'] = $item['thr-parent'];
1311 $data = self::createAnnounce($item, $data);
1313 } elseif ($data['type'] == 'Follow') {
1314 $data['object'] = $item['parent-uri'];
1315 } elseif ($data['type'] == 'Undo') {
1316 $data['object'] = self::createActivityFromItem($item_id, true);
1318 $data['diaspora:guid'] = $item['guid'];
1319 if (!empty($item['signed_text'])) {
1320 $data['diaspora:like'] = $item['signed_text'];
1322 $data['object'] = $item['thr-parent'];
1325 if (!empty($item['contact-uid'])) {
1326 $uid = $item['contact-uid'];
1328 $uid = $item['uid'];
1331 $owner = User::getOwnerDataById($uid);
1333 Logger::info('Fetched activity', ['item' => $item_id, 'uid' => $uid]);
1335 // We don't sign if we aren't the actor. This is important for relaying content especially for forums
1336 if (!$object_mode && !empty($owner) && ($data['actor'] == $owner['url'])) {
1337 return LDSignature::sign($data, $owner);
1342 /// @todo Create "conversation" entry
1346 * Creates a location entry for a given item array
1348 * @param array $item
1350 * @return array with location array
1352 private static function createLocation($item)
1354 $location = ['type' => 'Place'];
1356 if (!empty($item['location'])) {
1357 $location['name'] = $item['location'];
1362 if (empty($item['coord'])) {
1363 $coord = Map::getCoordinates($item['location']);
1365 $coords = explode(' ', $item['coord']);
1366 if (count($coords) == 2) {
1367 $coord = ['lat' => $coords[0], 'lon' => $coords[1]];
1371 if (!empty($coord['lat']) && !empty($coord['lon'])) {
1372 $location['latitude'] = $coord['lat'];
1373 $location['longitude'] = $coord['lon'];
1380 * Returns a tag array for a given item array
1382 * @param array $item
1384 * @return array of tags
1385 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1387 private static function createTagList($item)
1391 $terms = Tag::getByURIId($item['uri-id'], [Tag::HASHTAG, Tag::MENTION, Tag::IMPLICIT_MENTION, Tag::EXCLUSIVE_MENTION]);
1392 foreach ($terms as $term) {
1393 if ($term['type'] == Tag::HASHTAG) {
1394 $url = DI::baseUrl() . '/search?tag=' . urlencode($term['name']);
1395 $tags[] = ['type' => 'Hashtag', 'href' => $url, 'name' => '#' . $term['name']];
1397 $contact = Contact::getByURL($term['url'], false, ['addr']);
1398 if (empty($contact)) {
1401 if (!empty($contact['addr'])) {
1402 $mention = '@' . $contact['addr'];
1404 $mention = '@' . $term['url'];
1407 $tags[] = ['type' => 'Mention', 'href' => $term['url'], 'name' => $mention];
1411 $announce = self::getAnnounceArray($item);
1412 // Mention the original author upon commented reshares
1413 if (!empty($announce['comment'])) {
1414 $tags[] = ['type' => 'Mention', 'href' => $announce['actor']['url'], 'name' => '@' . $announce['actor']['addr']];
1421 * Adds attachment data to the JSON document
1423 * @param array $item Data of the item that is to be posted
1424 * @param string $type Object type
1426 * @return array with attachment data
1427 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1429 private static function createAttachmentList($item, $type)
1433 $uriids = [$item['uri-id']];
1434 $shared = BBCode::fetchShareAttributes($item['body']);
1435 if (!empty($shared['guid'])) {
1436 $shared_item = Post::selectFirst(['uri-id'], ['guid' => $shared['guid']]);
1437 if (!empty($shared_item['uri-id'])) {
1438 $uriids[] = $shared_item['uri-id'];
1443 foreach ($uriids as $uriid) {
1444 foreach (Post\Media::getByURIId($uriid, [Post\Media::AUDIO, Post\Media::IMAGE, Post\Media::VIDEO, Post\Media::DOCUMENT, Post\Media::TORRENT]) as $attachment) {
1445 if (in_array($attachment['url'], $urls)) {
1448 $urls[] = $attachment['url'];
1450 $attach = ['type' => 'Document',
1451 'mediaType' => $attachment['mimetype'],
1452 'url' => $attachment['url'],
1453 'name' => $attachment['description']];
1455 if (!empty($attachment['height'])) {
1456 $attach['height'] = $attachment['height'];
1459 if (!empty($attachment['width'])) {
1460 $attach['width'] = $attachment['width'];
1463 if (!empty($attachment['preview'])) {
1464 $attach['image'] = $attachment['preview'];
1467 $attachments[] = $attach;
1471 return $attachments;
1475 * Callback function to replace a Friendica style mention in a mention for a summary
1477 * @param array $match Matching values for the callback
1478 * @return string Replaced mention
1479 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1481 private static function mentionAddrCallback($match)
1483 if (empty($match[1])) {
1487 $data = Contact::getByURL($match[1], false, ['addr']);
1488 if (empty($data['addr'])) {
1492 return '@' . $data['addr'];
1496 * Remove image elements since they are added as attachment
1498 * @param string $body
1500 * @return string with removed images
1502 private static function removePictures($body)
1504 // Simplify image codes
1505 $body = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '[img]$3[/img]', $body);
1506 $body = preg_replace("/\[img\=(.*?)\](.*?)\[\/img\]/ism", '[img]$1[/img]', $body);
1508 // Now remove local links
1509 $body = preg_replace_callback(
1510 '/\[url=([^\[\]]*)\]\[img\](.*)\[\/img\]\[\/url\]/Usi',
1512 // We remove the link when it is a link to a local photo page
1513 if (Photo::isLocalPage($match[1])) {
1516 // otherwise we just return the link
1517 return '[url]' . $match[1] . '[/url]';
1522 // Remove all pictures
1523 $body = preg_replace("/\[img\]([^\[\]]*)\[\/img\]/Usi", '', $body);
1529 * Fetches the "context" value for a givem item array from the "conversation" table
1531 * @param array $item
1533 * @return string with context url
1534 * @throws \Exception
1536 private static function fetchContextURLForItem($item)
1538 $conversation = DBA::selectFirst('conversation', ['conversation-href', 'conversation-uri'], ['item-uri' => $item['parent-uri']]);
1539 if (DBA::isResult($conversation) && !empty($conversation['conversation-href'])) {
1540 $context_uri = $conversation['conversation-href'];
1541 } elseif (DBA::isResult($conversation) && !empty($conversation['conversation-uri'])) {
1542 $context_uri = $conversation['conversation-uri'];
1544 $context_uri = $item['parent-uri'] . '#context';
1546 return $context_uri;
1550 * Returns if the post contains sensitive content ("nsfw")
1552 * @param integer $uri_id
1555 * @throws \Exception
1557 private static function isSensitive($uri_id)
1559 return DBA::exists('tag-view', ['uri-id' => $uri_id, 'name' => 'nsfw', 'type' => Tag::HASHTAG]);
1563 * Creates event data
1565 * @param array $item
1567 * @return array with the event data
1568 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1570 private static function createEvent($item)
1573 $event['name'] = $item['event-summary'];
1574 $event['content'] = BBCode::convertForUriId($item['uri-id'], $item['event-desc'], BBCode::ACTIVITYPUB);
1575 $event['startTime'] = DateTimeFormat::utc($item['event-start'], 'c');
1577 if (!$item['event-nofinish']) {
1578 $event['endTime'] = DateTimeFormat::utc($item['event-finish'], 'c');
1581 if (!empty($item['event-location'])) {
1582 $item['location'] = $item['event-location'];
1583 $event['location'] = self::createLocation($item);
1586 // 2021.12: Backward compatibility value, all the events now "adjust" to the viewer timezone
1587 $event['dfrn:adjust'] = true;
1593 * Creates a note/article object array
1595 * @param array $item
1597 * @return array with the object data
1598 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1599 * @throws \ImagickException
1601 public static function createNote($item)
1607 // We are treating posts differently when they are directed to a community.
1608 // This is done to better support Lemmy. Most of the changes should work with other systems as well.
1609 // But to not risk compatibility issues we currently perform the changes only for communities.
1610 if ($item['gravity'] == GRAVITY_PARENT) {
1611 $isCommunityPost = !empty(Tag::getByURIId($item['uri-id'], [Tag::EXCLUSIVE_MENTION]));
1612 $links = Post\Media::getByURIId($item['uri-id'], [Post\Media::HTML]);
1613 if ($isCommunityPost && (count($links) == 1)) {
1614 $link = $links[0]['url'];
1617 $isCommunityPost = false;
1620 if ($item['event-type'] == 'event') {
1622 } elseif (!empty($item['title'])) {
1623 if (!$isCommunityPost || empty($link)) {
1626 // "Page" is used by Lemmy for posts that contain an external link
1633 if ($item['deleted']) {
1634 $type = 'Tombstone';
1638 $data['id'] = $item['uri'];
1639 $data['type'] = $type;
1641 if ($item['deleted']) {
1645 $data['summary'] = BBCode::toPlaintext(BBCode::getAbstract($item['body'], Protocol::ACTIVITYPUB));
1647 if ($item['uri'] != $item['thr-parent']) {
1648 $data['inReplyTo'] = $item['thr-parent'];
1650 $data['inReplyTo'] = null;
1653 $data['diaspora:guid'] = $item['guid'];
1654 $data['published'] = DateTimeFormat::utc($item['created'] . '+00:00', DateTimeFormat::ATOM);
1656 if ($item['created'] != $item['edited']) {
1657 $data['updated'] = DateTimeFormat::utc($item['edited'] . '+00:00', DateTimeFormat::ATOM);
1660 $data['url'] = $link ?? $item['plink'];
1661 $data['attributedTo'] = $item['author-link'];
1662 $data['sensitive'] = self::isSensitive($item['uri-id']);
1663 $data['context'] = self::fetchContextURLForItem($item);
1665 if (!empty($item['title'])) {
1666 $data['name'] = BBCode::toPlaintext($item['title'], false);
1669 $permission_block = self::createPermissionBlockForItem($item, false);
1671 $body = $item['body'];
1673 if ($type == 'Note') {
1674 $body = $item['raw-body'] ?? self::removePictures($body);
1678 * @todo Improve the automated summary
1679 * This part is currently deactivated. The automated summary seems to be more
1680 * confusing than helping. But possibly we will find a better way.
1681 * So the code is left here for now as a reminder
1683 * } elseif (($type == 'Article') && empty($data['summary'])) {
1684 * $regexp = "/[@!]\[url\=([^\[\]]*)\].*?\[\/url\]/ism";
1685 * $summary = preg_replace_callback($regexp, ['self', 'mentionAddrCallback'], $body);
1686 * $data['summary'] = BBCode::toPlaintext(Plaintext::shorten(self::removePictures($summary), 1000));
1690 if (empty($item['uid']) || !Feature::isEnabled($item['uid'], 'explicit_mentions')) {
1691 $body = self::prependMentions($body, $item['uri-id'], $item['author-link']);
1694 if ($type == 'Event') {
1695 $data = array_merge($data, self::createEvent($item));
1697 if ($isCommunityPost) {
1698 // For community posts we remove the visible "!user@domain.tld".
1699 // This improves the look at systems like Lemmy.
1700 // Also in the future we should control the community delivery via other methods.
1701 $body = preg_replace("/!\[url\=[^\[\]]*\][^\[\]]*\[\/url\]/ism", '', $body);
1704 if ($type == 'Page') {
1705 // When we transmit "Page" posts we have to remove the attachment.
1706 // The attachment contains the link that we already transmit in the "url" field.
1707 $body = preg_replace("/\s*\[attachment .*?\].*?\[\/attachment\]\s*/ism", '', $body);
1710 $body = BBCode::setMentionsToNicknames($body);
1712 $data['content'] = BBCode::convertForUriId($item['uri-id'], $body, BBCode::ACTIVITYPUB);
1715 // The regular "content" field does contain a minimized HTML. This is done since systems like
1716 // Mastodon has got problems with - for example - embedded pictures.
1717 // The contentMap does contain the unmodified HTML.
1718 $language = self::getLanguage($item);
1719 if (!empty($language)) {
1720 $richbody = BBCode::setMentionsToNicknames($item['body'] ?? '');
1721 $richbody = BBCode::removeAttachment($richbody);
1723 $data['contentMap'][$language] = BBCode::convertForUriId($item['uri-id'], $richbody, BBCode::EXTERNAL);
1726 $data['source'] = ['content' => $item['body'], 'mediaType' => "text/bbcode"];
1728 if (!empty($item['signed_text']) && ($item['uri'] != $item['thr-parent'])) {
1729 $data['diaspora:comment'] = $item['signed_text'];
1732 $data['attachment'] = self::createAttachmentList($item, $type);
1733 $data['tag'] = self::createTagList($item);
1735 if (empty($data['location']) && (!empty($item['coord']) || !empty($item['location']))) {
1736 $data['location'] = self::createLocation($item);
1739 if (!empty($item['app'])) {
1740 $data['generator'] = ['type' => 'Application', 'name' => $item['app']];
1743 $data = array_merge($data, $permission_block);
1749 * Fetches the language from the post, the user or the system.
1751 * @param array $item
1753 * @return string language string
1755 private static function getLanguage(array $item)
1757 // Try to fetch the language from the post itself
1758 if (!empty($item['language'])) {
1759 $languages = array_keys(json_decode($item['language'], true));
1760 if (!empty($languages[0])) {
1761 return $languages[0];
1765 // Otherwise use the user's language
1766 if (!empty($item['uid'])) {
1767 $user = DBA::selectFirst('user', ['language'], ['uid' => $item['uid']]);
1768 if (!empty($user['language'])) {
1769 return $user['language'];
1773 // And finally just use the system language
1774 return DI::config()->get('system', 'language');
1778 * Creates an an "add tag" entry
1780 * @param array $item
1781 * @param array $data activity data
1783 * @return array with activity data for adding tags
1784 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1785 * @throws \ImagickException
1787 private static function createAddTag($item, $data)
1789 $object = XML::parseString($item['object']);
1790 $target = XML::parseString($item["target"]);
1792 $data['diaspora:guid'] = $item['guid'];
1793 $data['actor'] = $item['author-link'];
1794 $data['target'] = (string)$target->id;
1795 $data['summary'] = BBCode::toPlaintext($item['body']);
1796 $data['object'] = ['id' => (string)$object->id, 'type' => 'tag', 'name' => (string)$object->title, 'content' => (string)$object->content];
1802 * Creates an announce object entry
1804 * @param array $item
1805 * @param array $data activity data
1807 * @return array with activity data
1808 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1809 * @throws \ImagickException
1811 private static function createAnnounce($item, $data)
1813 $orig_body = $item['body'];
1814 $announce = self::getAnnounceArray($item);
1815 if (empty($announce)) {
1816 $data['type'] = 'Create';
1817 $data['object'] = self::createNote($item);
1821 if (empty($announce['comment'])) {
1822 // Pure announce, without a quote
1823 $data['type'] = 'Announce';
1824 $data['object'] = $announce['object']['uri'];
1829 $data['type'] = 'Create';
1830 $item['body'] = $announce['comment'] . "\n" . $announce['object']['plink'];
1831 $data['object'] = self::createNote($item);
1833 /// @todo Finally descide how to implement this in AP. This is a possible way:
1834 $data['object']['attachment'][] = self::createNote($announce['object']);
1836 $data['object']['source']['content'] = $orig_body;
1841 * Return announce related data if the item is an annunce
1843 * @param array $item
1847 public static function getAnnounceArray($item)
1849 $reshared = Item::getShareArray($item);
1850 if (empty($reshared['guid'])) {
1854 $reshared_item = Post::selectFirst(Item::DELIVER_FIELDLIST, ['guid' => $reshared['guid']]);
1855 if (!DBA::isResult($reshared_item)) {
1859 if (!in_array($reshared_item['network'], [Protocol::ACTIVITYPUB, Protocol::DFRN])) {
1863 $profile = APContact::getByURL($reshared_item['author-link'], false);
1864 if (empty($profile)) {
1868 return ['object' => $reshared_item, 'actor' => $profile, 'comment' => $reshared['comment']];
1872 * Checks if the provided item array is an announce
1874 * @param array $item
1878 public static function isAnnounce($item)
1880 if (!empty($item['verb']) && ($item['verb'] == Activity::ANNOUNCE)) {
1884 $announce = self::getAnnounceArray($item);
1885 if (empty($announce)) {
1889 return empty($announce['comment']);
1893 * Creates an activity id for a given contact id
1895 * @param integer $cid Contact ID of target
1897 * @return bool|string activity id
1899 public static function activityIDFromContact($cid)
1901 $contact = DBA::selectFirst('contact', ['uid', 'id', 'created'], ['id' => $cid]);
1902 if (!DBA::isResult($contact)) {
1906 $hash = hash('ripemd128', $contact['uid'].'-'.$contact['id'].'-'.$contact['created']);
1907 $uuid = substr($hash, 0, 8). '-' . substr($hash, 8, 4) . '-' . substr($hash, 12, 4) . '-' . substr($hash, 16, 4) . '-' . substr($hash, 20, 12);
1908 return DI::baseUrl() . '/activity/' . $uuid;
1912 * Transmits a contact suggestion to a given inbox
1914 * @param integer $uid User ID
1915 * @param string $inbox Target inbox
1916 * @param integer $suggestion_id Suggestion ID
1918 * @return boolean was the transmission successful?
1919 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1921 public static function sendContactSuggestion($uid, $inbox, $suggestion_id)
1923 $owner = User::getOwnerDataById($uid);
1925 $suggestion = DI::fsuggest()->selectOneById($suggestion_id);
1927 $data = ['@context' => ActivityPub::CONTEXT,
1928 'id' => DI::baseUrl() . '/activity/' . System::createGUID(),
1929 'type' => 'Announce',
1930 'actor' => $owner['url'],
1931 'object' => $suggestion->url,
1932 'content' => $suggestion->note,
1933 'instrument' => self::getService(),
1934 'to' => [ActivityPub::PUBLIC_COLLECTION],
1937 $signed = LDSignature::sign($data, $owner);
1939 Logger::info('Deliver profile deletion for user ' . $uid . ' to ' . $inbox . ' via ActivityPub');
1940 return HTTPSignature::transmit($signed, $inbox, $uid);
1944 * Transmits a profile relocation to a given inbox
1946 * @param integer $uid User ID
1947 * @param string $inbox Target inbox
1949 * @return boolean was the transmission successful?
1950 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1952 public static function sendProfileRelocation($uid, $inbox)
1954 $owner = User::getOwnerDataById($uid);
1956 $data = ['@context' => ActivityPub::CONTEXT,
1957 'id' => DI::baseUrl() . '/activity/' . System::createGUID(),
1958 'type' => 'dfrn:relocate',
1959 'actor' => $owner['url'],
1960 'object' => $owner['url'],
1961 'published' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
1962 'instrument' => self::getService(),
1963 'to' => [ActivityPub::PUBLIC_COLLECTION],
1966 $signed = LDSignature::sign($data, $owner);
1968 Logger::info('Deliver profile relocation for user ' . $uid . ' to ' . $inbox . ' via ActivityPub');
1969 return HTTPSignature::transmit($signed, $inbox, $uid);
1973 * Transmits a profile deletion to a given inbox
1975 * @param integer $uid User ID
1976 * @param string $inbox Target inbox
1978 * @return boolean was the transmission successful?
1979 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1981 public static function sendProfileDeletion($uid, $inbox)
1983 $owner = User::getOwnerDataById($uid);
1985 if (empty($owner)) {
1986 Logger::error('No owner data found, the deletion message cannot be processed.', ['user' => $uid]);
1990 if (empty($owner['uprvkey'])) {
1991 Logger::error('No private key for owner found, the deletion message cannot be processed.', ['user' => $uid]);
1995 $data = ['@context' => ActivityPub::CONTEXT,
1996 'id' => DI::baseUrl() . '/activity/' . System::createGUID(),
1998 'actor' => $owner['url'],
1999 'object' => $owner['url'],
2000 'published' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
2001 'instrument' => self::getService(),
2002 'to' => [ActivityPub::PUBLIC_COLLECTION],
2005 $signed = LDSignature::sign($data, $owner);
2007 Logger::info('Deliver profile deletion for user ' . $uid . ' to ' . $inbox . ' via ActivityPub');
2008 return HTTPSignature::transmit($signed, $inbox, $uid);
2012 * Transmits a profile change to a given inbox
2014 * @param integer $uid User ID
2015 * @param string $inbox Target inbox
2017 * @return boolean was the transmission successful?
2018 * @throws HTTPException\InternalServerErrorException
2019 * @throws HTTPException\NotFoundException
2020 * @throws \ImagickException
2022 public static function sendProfileUpdate(int $uid, string $inbox): bool
2024 $owner = User::getOwnerDataById($uid);
2025 $profile = APContact::getByURL($owner['url']);
2027 $data = ['@context' => ActivityPub::CONTEXT,
2028 'id' => DI::baseUrl() . '/activity/' . System::createGUID(),
2030 'actor' => $owner['url'],
2031 'object' => self::getProfile($uid),
2032 'published' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
2033 'instrument' => self::getService(),
2034 'to' => [$profile['followers']],
2037 $signed = LDSignature::sign($data, $owner);
2039 Logger::info('Deliver profile update for user ' . $uid . ' to ' . $inbox . ' via ActivityPub');
2040 return HTTPSignature::transmit($signed, $inbox, $uid);
2044 * Transmits a given activity to a target
2046 * @param string $activity Type name
2047 * @param string $target Target profile
2048 * @param integer $uid User ID
2050 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2051 * @throws \ImagickException
2052 * @throws \Exception
2054 public static function sendActivity($activity, $target, $uid, $id = '')
2056 $profile = APContact::getByURL($target);
2057 if (empty($profile['inbox'])) {
2058 Logger::warning('No inbox found for target', ['target' => $target, 'profile' => $profile]);
2062 $owner = User::getOwnerDataById($uid);
2065 $id = DI::baseUrl() . '/activity/' . System::createGUID();
2068 $data = ['@context' => ActivityPub::CONTEXT,
2070 'type' => $activity,
2071 'actor' => $owner['url'],
2072 'object' => $profile['url'],
2073 'instrument' => self::getService(),
2074 'to' => [$profile['url']]];
2076 Logger::info('Sending activity ' . $activity . ' to ' . $target . ' for user ' . $uid);
2078 $signed = LDSignature::sign($data, $owner);
2079 return HTTPSignature::transmit($signed, $profile['inbox'], $uid);
2083 * Transmits a "follow object" activity to a target
2084 * This is a preparation for sending automated "follow" requests when receiving "Announce" messages
2086 * @param string $object Object URL
2087 * @param string $target Target profile
2088 * @param integer $uid User ID
2090 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2091 * @throws \ImagickException
2092 * @throws \Exception
2094 public static function sendFollowObject($object, $target, $uid = 0)
2096 $profile = APContact::getByURL($target);
2097 if (empty($profile['inbox'])) {
2098 Logger::warning('No inbox found for target', ['target' => $target, 'profile' => $profile]);
2103 // Fetch the list of administrators
2104 $admin_mail = explode(',', str_replace(' ', '', DI::config()->get('config', 'admin_email')));
2106 // We need to use some user as a sender. It doesn't care who it will send. We will use an administrator account.
2107 $condition = ['verified' => true, 'blocked' => false, 'account_removed' => false, 'account_expired' => false, 'email' => $admin_mail];
2108 $first_user = DBA::selectFirst('user', ['uid'], $condition);
2109 $uid = $first_user['uid'];
2112 $condition = ['verb' => Activity::FOLLOW, 'uid' => 0, 'parent-uri' => $object,
2113 'author-id' => Contact::getPublicIdByUserId($uid)];
2114 if (Post::exists($condition)) {
2115 Logger::info('Follow for ' . $object . ' for user ' . $uid . ' does already exist.');
2119 $owner = User::getOwnerDataById($uid);
2121 $data = ['@context' => ActivityPub::CONTEXT,
2122 'id' => DI::baseUrl() . '/activity/' . System::createGUID(),
2124 'actor' => $owner['url'],
2125 'object' => $object,
2126 'instrument' => self::getService(),
2127 'to' => [$profile['url']]];
2129 Logger::info('Sending follow ' . $object . ' to ' . $target . ' for user ' . $uid);
2131 $signed = LDSignature::sign($data, $owner);
2132 return HTTPSignature::transmit($signed, $profile['inbox'], $uid);
2136 * Transmit a message that the contact request had been accepted
2138 * @param string $target Target profile
2140 * @param integer $uid User ID
2141 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2142 * @throws \ImagickException
2144 public static function sendContactAccept($target, $id, $uid)
2146 $profile = APContact::getByURL($target);
2147 if (empty($profile['inbox'])) {
2148 Logger::warning('No inbox found for target', ['target' => $target, 'profile' => $profile]);
2152 $owner = User::getOwnerDataById($uid);
2153 $data = ['@context' => ActivityPub::CONTEXT,
2154 'id' => DI::baseUrl() . '/activity/' . System::createGUID(),
2156 'actor' => $owner['url'],
2158 'id' => (string)$id,
2160 'actor' => $profile['url'],
2161 'object' => $owner['url']
2163 'instrument' => self::getService(),
2164 'to' => [$profile['url']]];
2166 Logger::debug('Sending accept to ' . $target . ' for user ' . $uid . ' with id ' . $id);
2168 $signed = LDSignature::sign($data, $owner);
2169 HTTPSignature::transmit($signed, $profile['inbox'], $uid);
2173 * Reject a contact request or terminates the contact relation
2175 * @param string $target Target profile
2177 * @param integer $uid User ID
2178 * @return bool Operation success
2179 * @throws HTTPException\InternalServerErrorException
2180 * @throws \ImagickException
2182 public static function sendContactReject($target, $id, $uid): bool
2184 $profile = APContact::getByURL($target);
2185 if (empty($profile['inbox'])) {
2186 Logger::warning('No inbox found for target', ['target' => $target, 'profile' => $profile]);
2190 $owner = User::getOwnerDataById($uid);
2191 $data = ['@context' => ActivityPub::CONTEXT,
2192 'id' => DI::baseUrl() . '/activity/' . System::createGUID(),
2194 'actor' => $owner['url'],
2196 'id' => (string)$id,
2198 'actor' => $profile['url'],
2199 'object' => $owner['url']
2201 'instrument' => self::getService(),
2202 'to' => [$profile['url']]];
2204 Logger::debug('Sending reject to ' . $target . ' for user ' . $uid . ' with id ' . $id);
2206 $signed = LDSignature::sign($data, $owner);
2207 return HTTPSignature::transmit($signed, $profile['inbox'], $uid);
2211 * Transmits a message that we don't want to follow this contact anymore
2213 * @param string $target Target profile
2214 * @param integer $uid User ID
2215 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2216 * @throws \ImagickException
2217 * @throws \Exception
2218 * @return bool success
2220 public static function sendContactUndo($target, $cid, $uid)
2222 $profile = APContact::getByURL($target);
2223 if (empty($profile['inbox'])) {
2224 Logger::warning('No inbox found for target', ['target' => $target, 'profile' => $profile]);
2228 $object_id = self::activityIDFromContact($cid);
2229 if (empty($object_id)) {
2233 $id = DI::baseUrl() . '/activity/' . System::createGUID();
2235 $owner = User::getOwnerDataById($uid);
2236 $data = ['@context' => ActivityPub::CONTEXT,
2239 'actor' => $owner['url'],
2240 'object' => ['id' => $object_id, 'type' => 'Follow',
2241 'actor' => $owner['url'],
2242 'object' => $profile['url']],
2243 'instrument' => self::getService(),
2244 'to' => [$profile['url']]];
2246 Logger::info('Sending undo to ' . $target . ' for user ' . $uid . ' with id ' . $id);
2248 $signed = LDSignature::sign($data, $owner);
2249 return HTTPSignature::transmit($signed, $profile['inbox'], $uid);
2252 private static function prependMentions($body, int $uriid, string $authorLink)
2256 foreach (Tag::getByURIId($uriid, [Tag::IMPLICIT_MENTION]) as $tag) {
2257 $profile = Contact::getByURL($tag['url'], false, ['addr', 'contact-type', 'nick']);
2258 if (!empty($profile['addr'])
2259 && $profile['contact-type'] != Contact::TYPE_COMMUNITY
2260 && !strstr($body, $profile['addr'])
2261 && !strstr($body, $tag['url'])
2262 && $tag['url'] !== $authorLink
2264 $mentions[] = '@[url=' . $tag['url'] . ']' . $profile['nick'] . '[/url]';
2268 $mentions[] = $body;
2270 return implode(' ', $mentions);