3 * @copyright Copyright (C) 2010-2023, 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;
25 use Friendica\Content\Feature;
26 use Friendica\Content\Text\BBCode;
27 use Friendica\Core\Cache\Enum\Duration;
28 use Friendica\Core\Logger;
29 use Friendica\Core\Protocol;
30 use Friendica\Core\System;
31 use Friendica\Database\DBA;
33 use Friendica\Model\APContact;
34 use Friendica\Model\Contact;
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:';
65 * Add relay servers to the list of inboxes
67 * @param array $inboxes
68 * @return array inboxes with added relay servers
70 public static function addRelayServerInboxes(array $inboxes = []): array
72 foreach (Relay::getList(['inbox']) as $contact) {
73 $inboxes[$contact['inbox']] = $contact['inbox'];
80 * Add relay servers to the list of inboxes
82 * @param array $inboxes
83 * @return array inboxes with added relay servers
85 public static function addRelayServerInboxesForItem(int $item_id, array $inboxes = []): array
87 $item = Post::selectFirst(['uid'], ['id' => $item_id]);
92 $relays = Relay::getDirectRelayList($item_id);
97 foreach ($relays as $relay) {
98 $contact = Contact::getByURLForUser($relay['url'], $item['uid'], false, ['id']);
99 $inboxes[$relay['batch']][] = $contact['id'] ?? 0;
105 * Subscribe to a relay and updates contact on success
107 * @param string $url Subscribe actor url
108 * @return bool success
110 public static function sendRelayFollow(string $url): bool
112 $contact = Contact::getByURL($url);
113 if (empty($contact)) {
117 $activity_id = self::activityIDFromContact($contact['id']);
118 $success = self::sendActivity('Follow', $url, 0, $activity_id);
120 Contact::update(['rel' => Contact::FRIEND], ['id' => $contact['id']]);
127 * Unsubscribe from a relay and updates contact on success or forced
129 * @param string $url Subscribe actor url
130 * @param bool $force Set the relay status as non follower even if unsubscribe hadn't worked
131 * @return bool success
133 public static function sendRelayUndoFollow(string $url, bool $force = false): bool
135 $contact = Contact::getByURL($url);
136 if (empty($contact)) {
140 $success = self::sendContactUndo($url, $contact['id'], User::getSystemAccount());
142 if ($success || $force) {
143 Contact::update(['rel' => Contact::NOTHING], ['id' => $contact['id']]);
150 * Collects a list of contacts of the given owner
152 * @param array $owner Owner array
153 * @param array $rel The relevant value(s) contact.rel should match
154 * @param string $module The name of the relevant AP endpoint module (followers|following)
155 * @param integer $page Page number
156 * @param string $requester URL of the requester
157 * @param boolean $nocache Wether to bypass caching
158 * @return array of owners
161 public static function getContacts(array $owner, array $rel, string $module, int $page = null, string $requester = null, bool $nocache = false): array
164 $cachekey = self::CACHEKEY_CONTACTS . $module . ':'. $owner['uid'];
165 $result = DI::cache()->get($cachekey);
166 if (!$nocache && !is_null($result)) {
173 'uid' => $owner['uid'],
182 $condition = DBA::mergeConditions($parameters, ["`url` IN (SELECT `url` FROM `apcontact`)"]);
184 $total = DBA::count('contact', $condition);
186 $modulePath = '/' . $module . '/';
188 $data = ['@context' => ActivityPub::CONTEXT];
189 $data['id'] = DI::baseUrl() . $modulePath . $owner['nickname'];
190 $data['type'] = 'OrderedCollection';
191 $data['totalItems'] = $total;
194 $data['id'] .= '?' . http_build_query(['page' => $page]);
197 // When we hide our friends we will only show the pure number but don't allow more.
198 $show_contacts = empty($owner['hide-friends']);
200 // Allow fetching the contact list when the requester is part of the list.
201 if (($owner['page-flags'] == User::PAGE_FLAGS_PRVGROUP) && !empty($requester)) {
202 $show_contacts = DBA::exists('contact', ['nurl' => Strings::normaliseLink($requester), 'uid' => $owner['uid'], 'blocked' => false]);
205 if (!$show_contacts) {
206 if (!empty($cachekey)) {
207 DI::cache()->set($cachekey, $data, Duration::DAY);
214 $data['first'] = DI::baseUrl() . $modulePath . $owner['nickname'] . '?page=1';
216 $data['type'] = 'OrderedCollectionPage';
219 $contacts = DBA::select('contact', ['url'], $condition, ['limit' => [($page - 1) * 100, 100]]);
220 while ($contact = DBA::fetch($contacts)) {
221 $list[] = $contact['url'];
223 DBA::close($contacts);
225 if (count($list) == 100) {
226 $data['next'] = DI::baseUrl() . $modulePath . $owner['nickname'] . '?page=' . ($page + 1);
229 $data['partOf'] = DI::baseUrl() . $modulePath . $owner['nickname'];
231 $data['orderedItems'] = $list;
234 if (!empty($cachekey)) {
235 DI::cache()->set($cachekey, $data, Duration::DAY);
242 * Public posts for the given owner
244 * @param array $owner Owner array
245 * @param integer $page Page number
246 * @param boolean $nocache Wether to bypass caching
248 * @return array of posts
249 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
250 * @throws \ImagickException
252 public static function getFeatured(array $owner, int $page = null, bool $nocache = false): array
255 $cachekey = self::CACHEKEY_FEATURED . $owner['uid'];
256 $result = DI::cache()->get($cachekey);
257 if (!$nocache && !is_null($result)) {
262 $owner_cid = Contact::getIdForURL($owner['url'], 0, false);
264 $condition = ["`uri-id` IN (SELECT `uri-id` FROM `collection-view` WHERE `cid` = ? AND `type` = ?)",
265 $owner_cid, Post\Collection::FEATURED];
267 $condition = DBA::mergeConditions($condition, [
268 'uid' => $owner['uid'],
269 'author-id' => $owner_cid,
270 'private' => [Item::PUBLIC, Item::UNLISTED],
271 'gravity' => [Item::GRAVITY_PARENT, Item::GRAVITY_COMMENT],
272 'network' => Protocol::FEDERATED,
273 'parent-network' => Protocol::FEDERATED,
279 $count = Post::count($condition);
281 $data = ['@context' => ActivityPub::CONTEXT];
282 $data['id'] = DI::baseUrl() . '/featured/' . $owner['nickname'];
283 $data['type'] = 'OrderedCollection';
284 $data['totalItems'] = $count;
287 $data['id'] .= '?' . http_build_query(['page' => $page]);
291 $items = Post::select(['id'], $condition, ['limit' => 20, 'order' => ['created' => true]]);
293 $data['type'] = 'OrderedCollectionPage';
294 $items = Post::select(['id'], $condition, ['limit' => [($page - 1) * 20, 20], 'order' => ['created' => true]]);
298 while ($item = Post::fetch($items)) {
299 $activity = self::createActivityFromItem($item['id'], true);
300 if (!empty($activity)) {
306 if (count($list) == 20) {
307 $data['next'] = DI::baseUrl() . '/featured/' . $owner['nickname'] . '?page=' . ($page + 1);
311 $data['partOf'] = DI::baseUrl() . '/featured/' . $owner['nickname'];
314 $data['orderedItems'] = $list;
316 if (!empty($cachekey)) {
317 DI::cache()->set($cachekey, $data, Duration::DAY);
324 * Return the service array containing information the used software and it's url
326 * @return array with service data
328 public static function getService(): array
332 'name' => App::PLATFORM . " '" . App::CODENAME . "' " . App::VERSION . '-' . DB_UPDATE_VERSION,
333 'url' => (string)DI::baseUrl()
338 * Return the ActivityPub profile of the given user
340 * @param int $uid User ID
341 * @return array with profile data
342 * @throws HTTPException\NotFoundException
343 * @throws HTTPException\InternalServerErrorException
345 public static function getProfile(int $uid): array
347 $owner = User::getOwnerDataById($uid);
348 if (!isset($owner['id'])) {
349 DI::logger()->error('Unable to find owner data for uid', ['uid' => $uid, 'callstack' => System::callstack(20)]);
350 throw new HTTPException\NotFoundException('User not found.');
353 $data = ['@context' => ActivityPub::CONTEXT];
354 $data['id'] = $owner['url'];
356 if (!empty($owner['guid'])) {
357 $data['diaspora:guid'] = $owner['guid'];
360 $data['type'] = ActivityPub::ACCOUNT_TYPES[$owner['account-type']];
363 $data['following'] = DI::baseUrl() . '/following/' . $owner['nick'];
364 $data['followers'] = DI::baseUrl() . '/followers/' . $owner['nick'];
365 $data['inbox'] = DI::baseUrl() . '/inbox/' . $owner['nick'];
366 $data['outbox'] = DI::baseUrl() . '/outbox/' . $owner['nick'];
367 $data['featured'] = DI::baseUrl() . '/featured/' . $owner['nick'];
369 $data['inbox'] = DI::baseUrl() . '/friendica/inbox';
372 $data['preferredUsername'] = $owner['nick'];
373 $data['name'] = $owner['name'];
375 if (!empty($owner['country-name'] . $owner['region'] . $owner['locality'])) {
376 $data['vcard:hasAddress'] = ['@type' => 'vcard:Home', 'vcard:country-name' => $owner['country-name'],
377 'vcard:region' => $owner['region'], 'vcard:locality' => $owner['locality']];
380 if (!empty($owner['about'])) {
381 $data['summary'] = BBCode::convertForUriId($owner['uri-id'] ?? 0, $owner['about'], BBCode::EXTERNAL);
384 if (!empty($owner['xmpp']) || !empty($owner['matrix'])) {
385 $data['vcard:hasInstantMessage'] = [];
387 if (!empty($owner['xmpp'])) {
388 $data['vcard:hasInstantMessage'][] = 'xmpp:' . $owner['xmpp'];
390 if (!empty($owner['matrix'])) {
391 $data['vcard:hasInstantMessage'][] = 'matrix:' . $owner['matrix'];
395 $data['url'] = $owner['url'];
396 $data['manuallyApprovesFollowers'] = in_array($owner['page-flags'], [User::PAGE_FLAGS_NORMAL, User::PAGE_FLAGS_PRVGROUP]);
397 $data['discoverable'] = (bool)$owner['net-publish'];
398 $data['publicKey'] = ['id' => $owner['url'] . '#main-key',
399 'owner' => $owner['url'],
400 'publicKeyPem' => $owner['pubkey']];
401 $data['endpoints'] = ['sharedInbox' => DI::baseUrl() . '/inbox'];
403 $data['icon'] = ['type' => 'Image', 'url' => User::getAvatarUrl($owner)];
405 $resourceid = Photo::ridFromURI($owner['photo']);
406 if (!empty($resourceid)) {
407 $photo = Photo::selectFirst(['type'], ["resource-id" => $resourceid]);
408 if (!empty($photo['type'])) {
409 $data['icon']['mediaType'] = $photo['type'];
413 if (!empty($owner['header'])) {
414 $data['image'] = ['type' => 'Image', 'url' => Contact::getHeaderUrlForId($owner['id'], '', $owner['updated'])];
416 $resourceid = Photo::ridFromURI($owner['header']);
417 if (!empty($resourceid)) {
418 $photo = Photo::selectFirst(['type'], ["resource-id" => $resourceid]);
419 if (!empty($photo['type'])) {
420 $data['image']['mediaType'] = $photo['type'];
427 foreach (DI::profileField()->selectByContactId(0, $uid) as $profile_field) {
429 'type' => 'PropertyValue',
430 'name' => $profile_field->label,
431 'value' => BBCode::convertForUriId($owner['uri-id'], $profile_field->value)
435 if (!empty($custom_fields)) {
436 $data['attachment'] = $custom_fields;
440 $data['generator'] = self::getService();
442 // tags: https://kitty.town/@inmysocks/100656097926961126.json
447 * Get a minimal actor array for the C2S API
449 * @param integer $cid
452 private static function getActorArrayByCid(int $cid): array
454 $contact = Contact::getById($cid);
456 'id' => $contact['url'],
457 'type' => $data['type'] = ActivityPub::ACCOUNT_TYPES[$contact['contact-type']],
458 'url' => $contact['alias'],
459 'preferredUsername' => $contact['nick'],
460 'name' => $contact['name'],
461 'icon' => ['type' => 'Image', 'url' => Contact::getAvatarUrlForId($cid, '', $contact['updated'])],
462 'image' => ['type' => 'Image', 'url' => Contact::getHeaderUrlForId($cid, '', $contact['updated'])],
463 'manuallyApprovesFollowers' => (bool)$contact['manually-approve'],
464 'discoverable' => !$contact['unsearchable'],
467 if (empty($data['url'])) {
468 $data['url'] = $data['id'];
475 * @param string $username
477 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
479 public static function getDeletedUser(string $username): array
482 '@context' => ActivityPub::CONTEXT,
483 'id' => DI::baseUrl() . '/profile/' . $username,
484 'type' => 'Tombstone',
485 'published' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
486 'updated' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
487 'deleted' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
492 * Returns an array with permissions of the thread parent of the given item array
496 * @return array with permissions
497 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
498 * @throws \ImagickException
500 private static function fetchPermissionBlockFromThreadParent(array $item): array
502 if (empty($item['thr-parent-id'])) {
506 $parent = Post::selectFirstPost(['author-link'], ['uri-id' => $item['thr-parent-id']]);
507 if (empty($parent)) {
512 'to' => [$parent['author-link']],
519 $parent_profile = APContact::getByURL($parent['author-link']);
521 $item_profile = APContact::getByURL($item['author-link']);
522 $exclude[] = $item['author-link'];
524 if ($item['gravity'] == Item::GRAVITY_PARENT) {
525 $exclude[] = $item['owner-link'];
528 $type = [Tag::TO => 'to', Tag::CC => 'cc', Tag::BTO => 'bto', Tag::BCC => 'bcc', Tag::AUDIENCE => 'audience'];
529 foreach (Tag::getByURIId($item['thr-parent-id'], [Tag::TO, Tag::CC, Tag::BTO, Tag::BCC, Tag::AUDIENCE]) as $receiver) {
530 if (!empty($parent_profile['followers']) && $receiver['url'] == $parent_profile['followers'] && !empty($item_profile['followers'])) {
531 $permissions[$type[$receiver['type']]][] = $item_profile['followers'];
532 } elseif (!in_array($receiver['url'], $exclude)) {
533 $permissions[$type[$receiver['type']]][] = $receiver['url'];
541 * Check if the given item id is from ActivityPub
543 * @param integer $item_id
544 * @return boolean "true" if the post is from ActivityPub
546 private static function isAPPost(int $item_id): bool
548 if (empty($item_id)) {
552 return Post::exists(['id' => $item_id, 'network' => Protocol::ACTIVITYPUB]);
556 * Creates an array of permissions from an item thread
558 * @param array $item Item array
559 * @param boolean $blindcopy addressing via "bcc" or "cc"?
560 * @param boolean $expand_followers Expand the list of followers
561 * @param integer $last_id Last item id for adding receivers
563 * @return array with permission data
564 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
565 * @throws \ImagickException
567 private static function createPermissionBlockForItem(array $item, bool $blindcopy, bool $expand_followers, int $last_id = 0): array
570 $last_id = $item['id'];
577 // Check if we should always deliver our stuff via BCC
578 if (!empty($item['uid'])) {
579 $owner = User::getOwnerDataById($item['uid']);
580 if (!empty($owner)) {
581 $always_bcc = $owner['hide-friends'];
582 $is_group = ($owner['account-type'] == User::ACCOUNT_TYPE_COMMUNITY) && $owner['manually-approve'];
584 $profile = APContact::getByURL($owner['url'], false);
585 $follower = $profile['followers'] ?? '';
589 if (DI::config()->get('system', 'ap_always_bcc')) {
593 $parent = Post::selectFirst(['causer-link', 'post-reason'], ['id' => $item['parent']]);
594 if (!empty($parent) && ($parent['post-reason'] == Item::PR_ANNOUNCEMENT) && !empty($parent['causer-link'])) {
595 $profile = APContact::getByURL($parent['causer-link'], false);
596 $is_group_thread = isset($profile['type']) && $profile['type'] == 'Group';
598 $is_group_thread = false;
604 $parent_tags = Tag::getByURIId($item['parent-uri-id'], [Tag::AUDIENCE, Tag::MENTION]);
605 if (!empty($parent_tags)) {
606 $is_group_thread = false;
607 foreach ($parent_tags as $tag) {
608 if ($tag['type'] != Tag::AUDIENCE) {
611 $profile = APContact::getByURL($tag['url'], false);
612 if (!empty($profile) && ($profile['type'] == 'Group')) {
613 $is_group_thread = true;
616 if ($is_group_thread) {
617 foreach ($parent_tags as $tag) {
618 if (($tag['type'] == Tag::MENTION) && ($tag['url'] == $profile['url'])) {
622 $exclusive = !$mention;
624 } elseif ($is_group_thread) {
625 foreach (Tag::getByURIId($item['parent-uri-id'], [Tag::MENTION, Tag::EXCLUSIVE_MENTION]) as $term) {
626 $profile = APContact::getByURL($term['url'], false);
627 if (!empty($profile) && ($profile['type'] == 'Group')) {
628 if ($term['type'] == Tag::EXCLUSIVE_MENTION) {
630 } elseif ($term['type'] == Tag::MENTION) {
637 if (self::isAnnounce($item) || self::isAPPost($last_id)) {
638 // Will be activated in a later step
639 $networks = Protocol::FEDERATED;
641 // For now only send to these contacts:
642 $networks = [Protocol::ACTIVITYPUB, Protocol::OSTATUS];
645 $data = ['to' => [], 'cc' => [], 'bcc' => [] , 'audience' => []];
647 if ($item['gravity'] == Item::GRAVITY_PARENT) {
648 $actor_profile = APContact::getByURL($item['owner-link']);
650 $actor_profile = APContact::getByURL($item['author-link']);
654 $terms = Tag::getByURIId($item['uri-id'], [Tag::MENTION, Tag::IMPLICIT_MENTION, Tag::EXCLUSIVE_MENTION]);
656 if ($item['private'] != Item::PRIVATE) {
657 // Directly mention the original author upon a quoted reshare.
658 // Else just ensure that the original author receives the reshare.
659 $announce = self::getAnnounceArray($item);
660 if (!empty($announce['comment'])) {
661 $data['to'][] = $announce['actor']['url'];
662 } elseif (!empty($announce)) {
663 $data['cc'][] = $announce['actor']['url'];
666 if (!$is_group_thread) {
667 $data = array_merge($data, self::fetchPermissionBlockFromThreadParent($item));
670 // Check if the item is completely public or unlisted
671 if ($item['private'] == Item::PUBLIC) {
672 $data['to'][] = ActivityPub::PUBLIC_COLLECTION;
674 $data['cc'][] = ActivityPub::PUBLIC_COLLECTION;
677 foreach ($terms as $term) {
678 $profile = APContact::getByURL($term['url'], false);
679 if (!empty($profile)) {
680 if ($term['type'] == Tag::EXCLUSIVE_MENTION) {
682 if (!empty($profile['followers']) && ($profile['type'] == 'Group')) {
683 $data['cc'][] = $profile['followers'];
684 $data['audience'][] = $profile['url'];
686 } elseif (($term['type'] == Tag::MENTION) && ($profile['type'] == 'Group')) {
689 $data['to'][] = $profile['url'];
692 if (!$exclusive && ($item['private'] == Item::UNLISTED)) {
693 $data['to'][] = $actor_profile['followers'];
696 $receiver_list = Item::enumeratePermissions($item, true, $expand_followers);
698 foreach ($terms as $term) {
699 $cid = Contact::getIdForURL($term['url'], $item['uid']);
700 if (!empty($cid) && in_array($cid, $receiver_list)) {
701 $contact = DBA::selectFirst('contact', ['url', 'network', 'protocol', 'gsid'], ['id' => $cid, 'network' => Protocol::FEDERATED]);
702 if (!DBA::isResult($contact) || !self::isAPContact($contact, $networks)) {
706 $profile = APContact::getByURL($term['url'], false);
707 if (!empty($profile)) {
708 if ($term['type'] == Tag::EXCLUSIVE_MENTION) {
710 if (!empty($profile['followers']) && ($profile['type'] == 'Group')) {
711 $data['cc'][] = $profile['followers'];
712 $data['audience'][] = $profile['url'];
714 } elseif (($term['type'] == Tag::MENTION) && ($profile['type'] == 'Group')) {
717 $data['to'][] = $profile['url'];
726 if ($is_group && !$exclusive && !empty($follower)) {
727 $data['cc'][] = $follower;
728 } elseif (!$exclusive) {
729 foreach ($receiver_list as $receiver) {
730 if ($receiver == -1) {
731 $data['to'][] = $actor_profile['followers'];
735 $contact = DBA::selectFirst('contact', ['url', 'hidden', 'network', 'protocol', 'gsid'], ['id' => $receiver, 'network' => Protocol::FEDERATED]);
736 if (!DBA::isResult($contact) || !self::isAPContact($contact, $networks)) {
740 if (!empty($profile = APContact::getByURL($contact['url'], false))) {
741 if ($contact['hidden'] || $always_bcc) {
742 $data['bcc'][] = $profile['url'];
744 $data['cc'][] = $profile['url'];
751 if (!empty($item['parent']) && (!$is_group_thread || ($item['private'] == Item::PRIVATE))) {
752 if ($item['private'] == Item::PRIVATE) {
753 $condition = ['parent' => $item['parent'], 'uri-id' => $item['thr-parent-id']];
755 $condition = ['parent' => $item['parent']];
757 $parents = Post::select(['id', 'author-link', 'owner-link', 'gravity', 'uri'], $condition, ['order' => ['id']]);
758 while ($parent = Post::fetch($parents)) {
759 if ($parent['gravity'] == Item::GRAVITY_PARENT) {
760 $profile = APContact::getByURL($parent['owner-link'], false);
761 if (!empty($profile)) {
762 if ($item['gravity'] != Item::GRAVITY_PARENT) {
763 // Comments to groups are directed to the group
764 // But comments to groups aren't directed to the followers collection
765 // This rule is only valid when the actor isn't the group.
766 // The group needs to transmit their content to their followers.
767 if (($profile['type'] == 'Group') && ($profile['url'] != ($actor_profile['url'] ?? ''))) {
768 $data['to'][] = $profile['url'];
770 $data['cc'][] = $profile['url'];
771 if (($item['private'] != Item::PRIVATE) && !empty($actor_profile['followers']) && (!$exclusive || !$is_group_thread)) {
772 $data['cc'][] = $actor_profile['followers'];
775 } elseif (!$exclusive && !$is_group_thread) {
776 // Public thread parent post always are directed to the followers.
777 if ($item['private'] != Item::PRIVATE) {
778 $data['cc'][] = $actor_profile['followers'];
784 // Don't include data from future posts
785 if ($parent['id'] >= $last_id) {
789 $profile = APContact::getByURL($parent['author-link'], false);
790 if (!empty($profile)) {
791 if (($profile['type'] == 'Group') || ($parent['uri'] == $item['thr-parent'])) {
792 $data['to'][] = $profile['url'];
794 $data['cc'][] = $profile['url'];
798 DBA::close($parents);
801 $data['to'] = array_unique($data['to']);
802 $data['cc'] = array_unique($data['cc']);
803 $data['bcc'] = array_unique($data['bcc']);
804 $data['audience'] = array_unique($data['audience']);
806 if (($key = array_search($item['author-link'], $data['to'])) !== false) {
807 unset($data['to'][$key]);
810 if (($key = array_search($item['author-link'], $data['cc'])) !== false) {
811 unset($data['cc'][$key]);
814 if (($key = array_search($item['author-link'], $data['bcc'])) !== false) {
815 unset($data['bcc'][$key]);
818 if (($key = array_search($item['author-link'], $data['audience'])) !== false) {
819 unset($data['audience'][$key]);
822 foreach ($data['to'] as $to) {
823 if (($key = array_search($to, $data['cc'])) !== false) {
824 unset($data['cc'][$key]);
827 if (($key = array_search($to, $data['bcc'])) !== false) {
828 unset($data['bcc'][$key]);
832 foreach ($data['cc'] as $cc) {
833 if (($key = array_search($cc, $data['bcc'])) !== false) {
834 unset($data['bcc'][$key]);
838 $receivers = ['to' => array_values($data['to']), 'cc' => array_values($data['cc']), 'bcc' => array_values($data['bcc']), 'audience' => array_values($data['audience'])];
841 unset($receivers['bcc']);
844 foreach (['to' => Tag::TO, 'cc' => Tag::CC, 'bcc' => Tag::BCC, 'audience' => Tag::AUDIENCE] as $element => $type) {
845 if (!empty($receivers[$element])) {
846 foreach ($receivers[$element] as $receiver) {
847 if ($receiver == ActivityPub::PUBLIC_COLLECTION) {
848 $name = Receiver::PUBLIC_COLLECTION;
850 $name = trim(parse_url($receiver, PHP_URL_PATH), '/');
852 Tag::store($item['uri-id'], $type, $name, $receiver);
857 if (!$blindcopy && count($receivers['audience']) == 1) {
858 $receivers['audience'] = $receivers['audience'][0];
859 } elseif (!$receivers['audience']) {
860 unset($receivers['audience']);
867 * Check if an inbox is archived
869 * @param string $url Inbox url
870 * @return boolean "true" if inbox is archived
872 public static function archivedInbox(string $url): bool
874 return DBA::exists('inbox-status', ['url' => $url, 'archive' => true]);
878 * Check if a given contact should be delivered via AP
880 * @param array $contact Contact array
881 * @param array $networks Array with networks
882 * @return bool Whether the used protocol matches ACTIVITYPUB
885 private static function isAPContact(array $contact, array $networks): bool
887 if (in_array($contact['network'], $networks) || ($contact['protocol'] == Protocol::ACTIVITYPUB)) {
891 return GServer::getProtocol($contact['gsid'] ?? 0) == Post\DeliveryData::ACTIVITYPUB;
895 * Fetches a list of inboxes of followers of a given user
897 * @param integer $uid User ID
898 * @param boolean $personal fetch personal inboxes
899 * @param boolean $all_ap Retrieve all AP enabled inboxes
900 * @return array of follower inboxes
901 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
902 * @throws \ImagickException
904 public static function fetchTargetInboxesforUser(int $uid, bool $personal = false, bool $all_ap = false): array
909 if (!empty($item['uid'])) {
910 $profile = User::getOwnerDataById($item['uid']);
911 if (!empty($profile)) {
912 $isGroup = $profile['account-type'] == User::ACCOUNT_TYPE_COMMUNITY;
917 // Will be activated in a later step
918 $networks = Protocol::FEDERATED;
920 // For now only send to these contacts:
921 $networks = [Protocol::ACTIVITYPUB, Protocol::OSTATUS];
929 'network' => Protocol::FEDERATED,
933 $condition['rel'] = [Contact::FOLLOWER, Contact::FRIEND];
936 $contacts = DBA::select('contact', ['id', 'url', 'network', 'protocol', 'gsid'], $condition);
937 while ($contact = DBA::fetch($contacts)) {
938 if (!self::isAPContact($contact, $networks)) {
942 if ($isGroup && ($contact['network'] == Protocol::DFRN)) {
946 if (Network::isUrlBlocked($contact['url'])) {
950 $profile = APContact::getByURL($contact['url'], false);
951 if (!empty($profile)) {
952 if (empty($profile['sharedinbox']) || $personal || Contact::isLocal($contact['url'])) {
953 $target = $profile['inbox'];
955 $target = $profile['sharedinbox'];
957 if (!self::archivedInbox($target)) {
958 $inboxes[$target][] = $contact['id'];
962 DBA::close($contacts);
968 * Fetches an array of inboxes for the given item and user
970 * @param array $item Item array
971 * @param integer $uid User ID
972 * @param boolean $personal fetch personal inboxes
973 * @param integer $last_id Last item id for adding receivers
974 * @return array with inboxes
975 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
976 * @throws \ImagickException
978 public static function fetchTargetInboxes(array $item, int $uid, bool $personal = false, int $last_id = 0): array
980 $permissions = self::createPermissionBlockForItem($item, true, true, $last_id);
981 if (empty($permissions)) {
987 if ($item['gravity'] == Item::GRAVITY_ACTIVITY) {
988 $item_profile = APContact::getByURL($item['author-link'], false);
990 $item_profile = APContact::getByURL($item['owner-link'], false);
993 if (empty($item_profile)) {
997 $profile_uid = User::getIdForURL($item_profile['url']);
999 foreach (['to', 'cc', 'bto', 'bcc', 'audience'] as $element) {
1000 if (empty($permissions[$element])) {
1004 $blindcopy = in_array($element, ['bto', 'bcc']);
1006 foreach ($permissions[$element] as $receiver) {
1007 if (empty($receiver) || Network::isUrlBlocked($receiver)) {
1011 if ($item_profile && ($receiver == $item_profile['followers']) && ($uid == $profile_uid)) {
1012 $inboxes = array_merge($inboxes, self::fetchTargetInboxesforUser($uid, $personal, self::isAPPost($last_id)));
1014 $profile = APContact::getByURL($receiver, false);
1015 if (!empty($profile)) {
1016 $contact = Contact::getByURLForUser($receiver, $uid, false, ['id']);
1018 if (empty($profile['sharedinbox']) || $personal || $blindcopy || Contact::isLocal($receiver)) {
1019 $target = $profile['inbox'];
1021 $target = $profile['sharedinbox'];
1023 if (!self::archivedInbox($target) && !in_array($contact['id'], $inboxes[$target] ?? [])) {
1024 $inboxes[$target][] = $contact['id'] ?? 0;
1035 * Creates an array in the structure of the item table for a given mail id
1037 * @param integer $mail_id Mail id
1039 * @throws \Exception
1041 public static function getItemArrayFromMail(int $mail_id, bool $use_title = false): array
1043 $mail = DBA::selectFirst('mail', [], ['id' => $mail_id]);
1044 if (!DBA::isResult($mail)) {
1048 $reply = DBA::selectFirst('mail', ['uri', 'uri-id', 'from-url'], ['parent-uri' => $mail['parent-uri'], 'reply' => false]);
1049 if (!DBA::isResult($reply)) {
1053 // Making the post more compatible for Mastodon by:
1054 // - Making it a note and not an article (no title)
1055 // - Moving the title into the "summary" field that is used as a "content warning"
1058 $mail['body'] = '[abstract]' . $mail['title'] . "[/abstract]\n" . $mail['body'];
1059 $mail['title'] = '';
1062 $mail['content-warning'] = '';
1063 $mail['author-link'] = $mail['owner-link'] = $mail['from-url'];
1064 $mail['owner-id'] = $mail['author-id'];
1065 $mail['allow_cid'] = '<'.$mail['contact-id'].'>';
1066 $mail['allow_gid'] = '';
1067 $mail['deny_cid'] = '';
1068 $mail['deny_gid'] = '';
1069 $mail['private'] = Item::PRIVATE;
1070 $mail['deleted'] = false;
1071 $mail['edited'] = $mail['created'];
1072 $mail['plink'] = DI::baseUrl() . '/message/' . $mail['id'];
1073 $mail['parent-uri'] = $reply['uri'];
1074 $mail['parent-uri-id'] = $reply['uri-id'];
1075 $mail['parent-author-id'] = Contact::getIdForURL($reply['from-url'], 0, false);
1076 $mail['gravity'] = ($mail['reply'] ? Item::GRAVITY_COMMENT: Item::GRAVITY_PARENT);
1077 $mail['event-type'] = '';
1078 $mail['language'] = '';
1079 $mail['parent'] = 0;
1085 * Creates an activity array for a given mail id
1087 * @param integer $mail_id
1088 * @param boolean $object_mode Is the activity item is used inside another object?
1090 * @return array of activity
1091 * @throws \Exception
1093 public static function createActivityFromMail(int $mail_id, bool $object_mode = false): array
1095 $mail = self::getItemArrayFromMail($mail_id);
1099 $object = self::createNote($mail);
1101 if (!$object_mode) {
1102 $data = ['@context' => ActivityPub::CONTEXT];
1107 $data['id'] = $mail['uri'] . '/Create';
1108 $data['type'] = 'Create';
1109 $data['actor'] = $mail['author-link'];
1110 $data['published'] = DateTimeFormat::utc($mail['created'] . '+00:00', DateTimeFormat::ATOM);
1111 $data['instrument'] = self::getService();
1112 $data = array_merge($data, self::createPermissionBlockForItem($mail, true, false));
1114 if (empty($data['to']) && !empty($data['cc'])) {
1115 $data['to'] = $data['cc'];
1118 if (empty($data['to']) && !empty($data['bcc'])) {
1119 $data['to'] = $data['bcc'];
1123 unset($data['bcc']);
1124 unset($data['audience']);
1126 $object['to'] = $data['to'];
1127 $object['tag'] = [['type' => 'Mention', 'href' => $object['to'][0], 'name' => '']];
1129 unset($object['cc']);
1130 unset($object['bcc']);
1131 unset($object['audience']);
1133 $data['directMessage'] = true;
1135 $data['object'] = $object;
1137 $owner = User::getOwnerDataById($mail['uid']);
1139 if (!$object_mode && !empty($owner)) {
1140 return LDSignature::sign($data, $owner);
1147 * Returns the activity type of a given item
1149 * @param array $item Item array
1150 * @return string with activity type
1151 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1152 * @throws \ImagickException
1154 private static function getTypeOfItem(array $item): string
1158 // Only check for a reshare, if it is a real reshare and no quoted reshare
1159 if (strpos($item['body'], '[share') === 0) {
1160 $announce = self::getAnnounceArray($item);
1161 $reshared = !empty($announce);
1166 } elseif ($item['verb'] == Activity::POST) {
1167 if ($item['created'] == $item['edited']) {
1172 } elseif ($item['verb'] == Activity::LIKE) {
1174 } elseif ($item['verb'] == Activity::DISLIKE) {
1176 } elseif ($item['verb'] == Activity::ATTEND) {
1178 } elseif ($item['verb'] == Activity::ATTENDNO) {
1180 } elseif ($item['verb'] == Activity::ATTENDMAYBE) {
1181 $type = 'TentativeAccept';
1182 } elseif ($item['verb'] == Activity::FOLLOW) {
1184 } elseif ($item['verb'] == Activity::TAG) {
1186 } elseif ($item['verb'] == Activity::ANNOUNCE) {
1196 * Creates the activity or fetches it from the cache
1198 * @param integer $item_id Item id
1199 * @param boolean $force Force new cache entry
1200 * @return array|false activity or false on failure
1201 * @throws \Exception
1203 public static function createCachedActivityFromItem(int $item_id, bool $force = false, bool $object_mode = false)
1205 $cachekey = 'APDelivery:createActivity:' . $item_id . ':' . (int)$object_mode;
1208 $data = DI::cache()->get($cachekey);
1209 if (!is_null($data)) {
1214 $data = self::createActivityFromItem($item_id, $object_mode);
1216 DI::cache()->set($cachekey, $data, Duration::QUARTER_HOUR);
1221 * Creates an activity array for a given item id
1223 * @param integer $item_id
1224 * @param boolean $object_mode Is the activity item is used inside another object?
1225 * @param boolean $api_mode "true" if used for the API
1226 * @return false|array
1227 * @throws \Exception
1229 public static function createActivityFromItem(int $item_id, bool $object_mode = false, $api_mode = false)
1231 $condition = ['id' => $item_id];
1233 $condition['parent-network'] = Protocol::NATIVE_SUPPORT;
1235 Logger::info('Fetching activity', $condition);
1236 $item = Post::selectFirst(Item::DELIVER_FIELDLIST, $condition);
1237 if (!DBA::isResult($item)) {
1240 return self::createActivityFromArray($item, $object_mode, $api_mode);
1244 * Creates an activity array for a given URI-Id and uid
1246 * @param integer $uri_id
1247 * @param integer $uid
1248 * @param boolean $object_mode Is the activity item is used inside another object?
1249 * @param boolean $api_mode "true" if used for the API
1250 * @return false|array
1251 * @throws \Exception
1253 public static function createActivityFromUriId(int $uri_id, int $uid, bool $object_mode = false, $api_mode = false)
1255 $condition = ['uri-id' => $uri_id, 'uid' => [0, $uid]];
1257 $condition['parent-network'] = Protocol::NATIVE_SUPPORT;
1259 Logger::info('Fetching activity', $condition);
1260 $item = Post::selectFirst(Item::DELIVER_FIELDLIST, $condition, ['order' => ['uid' => true]]);
1261 if (!DBA::isResult($item)) {
1265 return self::createActivityFromArray($item, $object_mode, $api_mode);
1269 * Creates an activity array for a given item id
1271 * @param integer $item_id
1272 * @param boolean $object_mode Is the activity item is used inside another object?
1273 * @param boolean $api_mode "true" if used for the API
1274 * @return false|array
1275 * @throws \Exception
1277 private static function createActivityFromArray(array $item, bool $object_mode = false, $api_mode = false)
1279 if (!$api_mode && !$item['deleted'] && $item['network'] == Protocol::ACTIVITYPUB) {
1280 $data = Post\Activity::getByURIId($item['uri-id']);
1281 if (!$item['origin'] && !empty($data)) {
1282 if (!$object_mode) {
1283 Logger::info('Return stored conversation', ['item' => $item['id']]);
1285 } elseif (!empty($data['object'])) {
1286 Logger::info('Return stored conversation object', ['item' => $item['id']]);
1287 return $data['object'];
1292 if (!$api_mode && !$item['origin']) {
1293 Logger::debug('Post is not ours and is not stored', ['id' => $item['id'], 'uri-id' => $item['uri-id']]);
1297 $type = self::getTypeOfItem($item);
1299 if (!$object_mode) {
1300 $data = ['@context' => $context ?? ActivityPub::CONTEXT];
1302 if ($item['deleted'] && ($item['gravity'] == Item::GRAVITY_ACTIVITY)) {
1304 } elseif ($item['deleted']) {
1311 if ($type == 'Delete') {
1312 $data['id'] = Item::newURI($item['guid']) . '/' . $type;;
1313 } elseif (($item['gravity'] == Item::GRAVITY_ACTIVITY) && ($type != 'Undo')) {
1314 $data['id'] = $item['uri'];
1316 $data['id'] = $item['uri'] . '/' . $type;
1319 $data['type'] = $type;
1321 if (($type != 'Announce') || ($item['gravity'] != Item::GRAVITY_PARENT)) {
1322 $link = $item['author-link'];
1323 $id = $item['author-id'];
1325 $link = $item['owner-link'];
1326 $id = $item['owner-id'];
1330 $data['actor'] = self::getActorArrayByCid($id);
1332 $data['actor'] = $link;
1335 $data['published'] = DateTimeFormat::utc($item['created'] . '+00:00', DateTimeFormat::ATOM);
1337 $data['instrument'] = self::getService();
1339 $data = array_merge($data, self::createPermissionBlockForItem($item, false, false));
1341 if (in_array($data['type'], ['Create', 'Update', 'Delete'])) {
1342 $data['object'] = self::createNote($item, $api_mode);
1343 } elseif ($data['type'] == 'Add') {
1344 $data = self::createAddTag($item, $data);
1345 } elseif ($data['type'] == 'Announce') {
1346 if ($item['verb'] == ACTIVITY::ANNOUNCE) {
1347 $data['object'] = $item['thr-parent'];
1349 $data = self::createAnnounce($item, $data, $api_mode);
1351 } elseif ($data['type'] == 'Follow') {
1352 $data['object'] = $item['parent-uri'];
1353 } elseif ($data['type'] == 'Undo') {
1354 $data['object'] = self::createActivityFromItem($item['id'], true);
1356 $data['diaspora:guid'] = $item['guid'];
1357 if (!empty($item['signed_text'])) {
1358 $data['diaspora:like'] = $item['signed_text'];
1360 $data['object'] = $item['thr-parent'];
1363 if (!empty($item['contact-uid'])) {
1364 $uid = $item['contact-uid'];
1366 $uid = $item['uid'];
1369 Logger::info('Fetched activity', ['item' => $item['id'], 'uid' => $uid]);
1371 // We only sign our own activities
1372 if (!$api_mode && !$object_mode && $item['origin']) {
1373 $owner = User::getOwnerDataById($uid);
1374 return LDSignature::sign($data, $owner);
1379 /// @todo Create "conversation" entry
1383 * Creates a location entry for a given item array
1385 * @param array $item Item array
1386 * @return array with location array
1388 private static function createLocation(array $item): array
1390 $location = ['type' => 'Place'];
1392 if (!empty($item['location'])) {
1393 $location['name'] = $item['location'];
1398 if (empty($item['coord'])) {
1399 $coord = Map::getCoordinates($item['location']);
1401 $coords = explode(' ', $item['coord']);
1402 if (count($coords) == 2) {
1403 $coord = ['lat' => $coords[0], 'lon' => $coords[1]];
1407 if (!empty($coord['lat']) && !empty($coord['lon'])) {
1408 $location['latitude'] = $coord['lat'];
1409 $location['longitude'] = $coord['lon'];
1416 * Returns a tag array for a given item array
1418 * @param array $item Item array
1419 * @param string $quote_url Url of the attached quote link
1420 * @return array of tags
1421 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1423 private static function createTagList(array $item, string $quote_url): array
1427 $terms = Tag::getByURIId($item['uri-id'], [Tag::HASHTAG, Tag::MENTION, Tag::IMPLICIT_MENTION, Tag::EXCLUSIVE_MENTION]);
1428 foreach ($terms as $term) {
1429 if ($term['type'] == Tag::HASHTAG) {
1430 $url = DI::baseUrl() . '/search?tag=' . urlencode($term['name']);
1431 $tags[] = ['type' => 'Hashtag', 'href' => $url, 'name' => '#' . $term['name']];
1433 $contact = Contact::getByURL($term['url'], false, ['addr']);
1434 if (empty($contact)) {
1437 if (!empty($contact['addr'])) {
1438 $mention = '@' . $contact['addr'];
1440 $mention = '@' . $term['url'];
1443 $tags[] = ['type' => 'Mention', 'href' => $term['url'], 'name' => $mention];
1447 $announce = self::getAnnounceArray($item);
1448 // Mention the original author upon commented reshares
1449 if (!empty($announce['comment'])) {
1450 $tags[] = ['type' => 'Mention', 'href' => $announce['actor']['url'], 'name' => '@' . $announce['actor']['addr']];
1453 // @see https://codeberg.org/fediverse/fep/src/branch/main/feps/fep-e232.md
1454 if (!empty($quote_url)) {
1455 // Currently deactivated because of compatibility issues with Pleroma
1457 // 'type' => 'Link',
1458 // 'mediaType' => 'application/ld+json; profile="https://www.w3.org/ns/activitystreams"',
1459 // 'href' => $quote_url,
1460 // 'name' => '♲ ' . BBCode::convertForUriId($item['uri-id'], $quote_url, BBCode::ACTIVITYPUB)
1468 * Adds attachment data to the JSON document
1470 * @param array $item Data of the item that is to be posted
1472 * @return array with attachment data
1473 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1475 private static function createAttachmentList(array $item): array
1480 foreach (Post\Media::getByURIId($item['uri-id'], [Post\Media::AUDIO, Post\Media::IMAGE, Post\Media::VIDEO, Post\Media::DOCUMENT, Post\Media::TORRENT]) as $attachment) {
1481 if (in_array($attachment['url'], $urls)) {
1484 $urls[] = $attachment['url'];
1486 $attach = ['type' => 'Document',
1487 'mediaType' => $attachment['mimetype'],
1488 'url' => $attachment['url'],
1489 'name' => $attachment['description']];
1491 if (!empty($attachment['height'])) {
1492 $attach['height'] = $attachment['height'];
1495 if (!empty($attachment['width'])) {
1496 $attach['width'] = $attachment['width'];
1499 if (!empty($attachment['preview'])) {
1500 $attach['image'] = $attachment['preview'];
1503 $attachments[] = $attach;
1506 return $attachments;
1510 * Callback function to replace a Friendica style mention in a mention for a summary
1512 * @param array $match Matching values for the callback
1513 * @return string Replaced mention
1514 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1516 private static function mentionAddrCallback(array $match): string
1518 if (empty($match[1])) {
1522 $data = Contact::getByURL($match[1], false, ['addr']);
1523 if (empty($data['addr'])) {
1527 return '@' . $data['addr'];
1531 * Remove image elements since they are added as attachment
1533 * @param string $body HTML code
1534 * @return string with removed images
1536 private static function removePictures(string $body): string
1538 return BBCode::performWithEscapedTags($body, ['code', 'noparse', 'nobb', 'pre'], function ($text) {
1539 // Simplify image codes
1540 $text = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '[img]$3[/img]', $text);
1541 $text = preg_replace("/\[img\=(.*?)\](.*?)\[\/img\]/ism", '[img]$1[/img]', $text);
1543 // Now remove local links
1544 $text = preg_replace_callback(
1545 '/\[url=([^\[\]]*)\]\[img\](.*)\[\/img\]\[\/url\]/Usi',
1547 // We remove the link when it is a link to a local photo page
1548 if (Photo::isLocalPage($match[1])) {
1551 // otherwise we just return the link
1552 return '[url]' . $match[1] . '[/url]';
1557 // Remove all pictures
1558 return preg_replace("/\[img\]([^\[\]]*)\[\/img\]/Usi", '', $text);
1563 * Returns if the post contains sensitive content ("nsfw")
1565 * @param integer $uri_id URI id
1566 * @return boolean Whether URI id was found
1567 * @throws \Exception
1569 private static function isSensitive(int $uri_id): bool
1571 return DBA::exists('tag-view', ['uri-id' => $uri_id, 'name' => 'nsfw', 'type' => Tag::HASHTAG]);
1575 * Creates event data
1577 * @param array $item Item array
1578 * @return array with the event data
1579 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1581 private static function createEvent(array $item): array
1584 $event['name'] = $item['event-summary'];
1585 $event['content'] = BBCode::convertForUriId($item['uri-id'], $item['event-desc'], BBCode::ACTIVITYPUB);
1586 $event['startTime'] = DateTimeFormat::utc($item['event-start'], 'c');
1588 if (!$item['event-nofinish']) {
1589 $event['endTime'] = DateTimeFormat::utc($item['event-finish'], 'c');
1592 if (!empty($item['event-location'])) {
1593 $item['location'] = $item['event-location'];
1594 $event['location'] = self::createLocation($item);
1597 // 2021.12: Backward compatibility value, all the events now "adjust" to the viewer timezone
1598 $event['dfrn:adjust'] = true;
1604 * Creates a note/article object array
1606 * @param array $item
1607 * @param bool $api_mode
1608 * @return array with the object data
1609 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1610 * @throws \ImagickException
1612 public static function createNote(array $item, bool $api_mode = false): array
1618 // We are treating posts differently when they are directed to a community.
1619 // This is done to better support Lemmy. Most of the changes should work with other systems as well.
1620 // But to not risk compatibility issues we currently perform the changes only for communities.
1621 if ($item['gravity'] == Item::GRAVITY_PARENT) {
1622 $isCommunityPost = !empty(Tag::getByURIId($item['uri-id'], [Tag::EXCLUSIVE_MENTION]));
1623 $links = Post\Media::getByURIId($item['uri-id'], [Post\Media::HTML]);
1624 if ($isCommunityPost && (count($links) == 1)) {
1625 $link = $links[0]['url'];
1628 $isCommunityPost = false;
1631 if ($item['event-type'] == 'event') {
1633 } elseif (!empty($item['title'])) {
1634 if (!$isCommunityPost || empty($link)) {
1637 // "Page" is used by Lemmy for posts that contain an external link
1644 if ($item['deleted']) {
1645 $type = 'Tombstone';
1649 $data['id'] = $item['uri'];
1650 $data['type'] = $type;
1652 if ($item['deleted']) {
1656 $data['summary'] = BBCode::toPlaintext(BBCode::getAbstract($item['body'], Protocol::ACTIVITYPUB));
1658 if ($item['uri'] != $item['thr-parent']) {
1659 $data['inReplyTo'] = $item['thr-parent'];
1661 $data['inReplyTo'] = null;
1664 $data['diaspora:guid'] = $item['guid'];
1665 $data['published'] = DateTimeFormat::utc($item['created'] . '+00:00', DateTimeFormat::ATOM);
1667 if ($item['created'] != $item['edited']) {
1668 $data['updated'] = DateTimeFormat::utc($item['edited'] . '+00:00', DateTimeFormat::ATOM);
1671 $data['url'] = $link ?? $item['plink'];
1673 $data['attributedTo'] = self::getActorArrayByCid($item['author-id']);
1675 $data['attributedTo'] = $item['author-link'];
1677 $data['sensitive'] = self::isSensitive($item['uri-id']);
1679 if (!empty($item['conversation']) && ($item['conversation'] != './')) {
1680 $data['conversation'] = $data['context'] = $item['conversation'];
1683 if (!empty($item['title'])) {
1684 $data['name'] = BBCode::toPlaintext($item['title'], false);
1687 $permission_block = self::createPermissionBlockForItem($item, false, false);
1689 $real_quote = false;
1691 $item = Post\Media::addHTMLAttachmentToItem($item);
1693 $body = $item['body'];
1695 if ($type == 'Note') {
1696 $body = $item['raw-body'] ?? self::removePictures($body);
1700 * @todo Improve the automated summary
1701 * This part is currently deactivated. The automated summary seems to be more
1702 * confusing than helping. But possibly we will find a better way.
1703 * So the code is left here for now as a reminder
1705 * } elseif (($type == 'Article') && empty($data['summary'])) {
1706 * $regexp = "/[@!]\[url\=([^\[\]]*)\].*?\[\/url\]/ism";
1707 * $summary = preg_replace_callback($regexp, [self::class, 'mentionAddrCallback'], $body);
1708 * $data['summary'] = BBCode::toPlaintext(Plaintext::shorten(self::removePictures($summary), 1000));
1712 if (empty($item['uid']) || !Feature::isEnabled($item['uid'], 'explicit_mentions')) {
1713 $body = self::prependMentions($body, $item['uri-id'], $item['author-link']);
1716 if ($type == 'Event') {
1717 $data = array_merge($data, self::createEvent($item));
1719 if ($isCommunityPost) {
1720 // For community posts we remove the visible "!user@domain.tld".
1721 // This improves the look at systems like Lemmy.
1722 // Also in the future we should control the community delivery via other methods.
1723 $body = preg_replace("/!\[url\=[^\[\]]*\][^\[\]]*\[\/url\]/ism", '', $body);
1726 if ($type == 'Page') {
1727 // When we transmit "Page" posts we have to remove the attachment.
1728 // The attachment contains the link that we already transmit in the "url" field.
1729 $body = BBCode::removeAttachment($body);
1732 $body = BBCode::setMentionsToNicknames($body);
1734 if (!empty($item['quote-uri-id'])) {
1735 if (Post::exists(['uri-id' => $item['quote-uri-id'], 'network' => [Protocol::ACTIVITYPUB, Protocol::DFRN]])) {
1737 $data['quoteUrl'] = $item['quote-uri'];
1738 $body = DI::contentItem()->addShareLink($body, $item['quote-uri-id']);
1740 $body = DI::contentItem()->addSharedPost($item, $body);
1744 $data['content'] = BBCode::convertForUriId($item['uri-id'], $body, BBCode::ACTIVITYPUB);
1747 // The regular "content" field does contain a minimized HTML. This is done since systems like
1748 // Mastodon has got problems with - for example - embedded pictures.
1749 // The contentMap does contain the unmodified HTML.
1750 $language = self::getLanguage($item);
1751 if (!empty($language)) {
1752 $richbody = BBCode::setMentionsToNicknames($item['body'] ?? '');
1753 $richbody = Post\Media::removeFromEndOfBody($richbody);
1754 if (!empty($item['quote-uri-id'])) {
1756 $richbody = DI::contentItem()->addShareLink($richbody, $item['quote-uri-id']);
1758 $richbody = DI::contentItem()->addSharedPost($item, $richbody);
1761 $richbody = BBCode::replaceAttachment($richbody);
1763 $data['contentMap'][$language] = BBCode::convertForUriId($item['uri-id'], $richbody, BBCode::EXTERNAL);
1766 if (!empty($item['quote-uri-id'])) {
1767 $source = DI::contentItem()->addSharedPost($item, $item['body']);
1769 $source = $item['body'];
1772 $data['source'] = ['content' => $source, 'mediaType' => "text/bbcode"];
1774 if (!empty($item['signed_text']) && ($item['uri'] != $item['thr-parent'])) {
1775 $data['diaspora:comment'] = $item['signed_text'];
1778 $data['attachment'] = self::createAttachmentList($item);
1779 $data['tag'] = self::createTagList($item, $data['quoteUrl'] ?? '');
1781 if (empty($data['location']) && (!empty($item['coord']) || !empty($item['location']))) {
1782 $data['location'] = self::createLocation($item);
1785 if (!empty($item['app'])) {
1786 $data['generator'] = ['type' => 'Application', 'name' => $item['app']];
1789 $data = array_merge($data, $permission_block);
1795 * Fetches the language from the post, the user or the system.
1797 * @param array $item
1798 * @return string language string
1800 private static function getLanguage(array $item): string
1802 // Try to fetch the language from the post itself
1803 if (!empty($item['language'])) {
1804 $languages = array_keys(json_decode($item['language'], true));
1805 if (!empty($languages[0])) {
1806 return $languages[0];
1810 // Otherwise use the user's language
1811 if (!empty($item['uid'])) {
1812 $user = DBA::selectFirst('user', ['language'], ['uid' => $item['uid']]);
1813 if (!empty($user['language'])) {
1814 return $user['language'];
1818 // And finally just use the system language
1819 return DI::config()->get('system', 'language');
1823 * Creates an an "add tag" entry
1825 * @param array $item Item array
1826 * @param array $activity activity data
1827 * @return array with activity data for adding tags
1828 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1829 * @throws \ImagickException
1831 private static function createAddTag(array $item, array $activity): array
1833 $object = XML::parseString($item['object']);
1834 $target = XML::parseString($item['target']);
1836 $activity['diaspora:guid'] = $item['guid'];
1837 $activity['actor'] = $item['author-link'];
1838 $activity['target'] = (string)$target->id;
1839 $activity['summary'] = BBCode::toPlaintext($item['body']);
1840 $activity['object'] = ['id' => (string)$object->id, 'type' => 'tag', 'name' => (string)$object->title, 'content' => (string)$object->content];
1846 * Creates an announce object entry
1848 * @param array $item Item array
1849 * @param array $activity activity data
1850 * @param bool $api_mode
1851 * @return array with activity data
1852 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1853 * @throws \ImagickException
1855 private static function createAnnounce(array $item, array $activity, bool $api_mode = false): array
1857 $orig_body = $item['body'];
1858 $announce = self::getAnnounceArray($item);
1859 if (empty($announce)) {
1860 $activity['type'] = 'Create';
1861 $activity['object'] = self::createNote($item, $api_mode);
1865 if (empty($announce['comment'])) {
1866 // Pure announce, without a quote
1867 $activity['type'] = 'Announce';
1868 $activity['object'] = $announce['object']['uri'];
1873 $activity['type'] = 'Create';
1874 $item['body'] = $announce['comment'] . "\n" . $announce['object']['plink'];
1875 $activity['object'] = self::createNote($item, $api_mode);
1877 /// @todo Finally decide how to implement this in AP. This is a possible way:
1878 $activity['object']['attachment'][] = self::createNote($announce['object']);
1880 $activity['object']['source']['content'] = $orig_body;
1885 * Return announce related data if the item is an announce
1887 * @param array $item
1888 * @return array Announcement array
1890 private static function getAnnounceArray(array $item): array
1892 $reshared = DI::contentItem()->getSharedPost($item, Item::DELIVER_FIELDLIST);
1893 if (empty($reshared)) {
1897 if (!in_array($reshared['post']['network'], [Protocol::ACTIVITYPUB, Protocol::DFRN])) {
1901 $profile = APContact::getByURL($reshared['post']['author-link'], false);
1902 if (empty($profile)) {
1906 return ['object' => $reshared['post'], 'actor' => $profile, 'comment' => $reshared['comment']];
1910 * Checks if the provided item array is an announce
1912 * @param array $item Item array
1913 * @return boolean Whether item is an announcement
1915 public static function isAnnounce(array $item): bool
1917 if (!empty($item['verb']) && ($item['verb'] == Activity::ANNOUNCE)) {
1921 $announce = self::getAnnounceArray($item);
1922 if (empty($announce)) {
1926 return empty($announce['comment']);
1930 * Creates an activity id for a given contact id
1932 * @param integer $cid Contact ID of target
1934 * @return bool|string activity id
1936 public static function activityIDFromContact(int $cid)
1938 $contact = DBA::selectFirst('contact', ['uid', 'id', 'created'], ['id' => $cid]);
1939 if (!DBA::isResult($contact)) {
1943 $hash = hash('ripemd128', $contact['uid'].'-'.$contact['id'].'-'.$contact['created']);
1944 $uuid = substr($hash, 0, 8). '-' . substr($hash, 8, 4) . '-' . substr($hash, 12, 4) . '-' . substr($hash, 16, 4) . '-' . substr($hash, 20, 12);
1945 return DI::baseUrl() . '/activity/' . $uuid;
1949 * Transmits a contact suggestion to a given inbox
1951 * @param array $owner Sender owner-view record
1952 * @param string $inbox Target inbox
1953 * @param integer $suggestion_id Suggestion ID
1954 * @return boolean was the transmission successful?
1955 * @throws \Exception
1957 public static function sendContactSuggestion(array $owner, string $inbox, int $suggestion_id): bool
1959 $suggestion = DI::fsuggest()->selectOneById($suggestion_id);
1962 '@context' => ActivityPub::CONTEXT,
1963 'id' => DI::baseUrl() . '/activity/' . System::createGUID(),
1964 'type' => 'Announce',
1965 'actor' => $owner['url'],
1966 'object' => $suggestion->url,
1967 'content' => $suggestion->note,
1968 'instrument' => self::getService(),
1969 'to' => [ActivityPub::PUBLIC_COLLECTION],
1973 $signed = LDSignature::sign($data, $owner);
1975 Logger::info('Deliver profile deletion for user ' . $owner['uid'] . ' to ' . $inbox . ' via ActivityPub');
1976 return HTTPSignature::transmit($signed, $inbox, $owner);
1980 * Transmits a profile relocation to a given inbox
1982 * @param array $owner Sender owner-view record
1983 * @param string $inbox Target inbox
1984 * @return boolean was the transmission successful?
1985 * @throws \Exception
1987 public static function sendProfileRelocation(array $owner, string $inbox): bool
1990 '@context' => ActivityPub::CONTEXT,
1991 'id' => DI::baseUrl() . '/activity/' . System::createGUID(),
1992 'type' => 'dfrn:relocate',
1993 'actor' => $owner['url'],
1994 'object' => $owner['url'],
1995 'published' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
1996 'instrument' => self::getService(),
1997 'to' => [ActivityPub::PUBLIC_COLLECTION],
2001 $signed = LDSignature::sign($data, $owner);
2003 Logger::info('Deliver profile relocation for user ' . $owner['uid'] . ' to ' . $inbox . ' via ActivityPub');
2004 return HTTPSignature::transmit($signed, $inbox, $owner);
2008 * Transmits a profile deletion to a given inbox
2010 * @param array $owner Sender owner-view record
2011 * @param string $inbox Target inbox
2012 * @return boolean was the transmission successful?
2013 * @throws \Exception
2015 public static function sendProfileDeletion(array $owner, string $inbox): bool
2017 if (empty($owner['uprvkey'])) {
2018 Logger::error('No private key for owner found, the deletion message cannot be processed.', ['user' => $owner['uid']]);
2022 $data = ['@context' => ActivityPub::CONTEXT,
2023 'id' => DI::baseUrl() . '/activity/' . System::createGUID(),
2025 'actor' => $owner['url'],
2026 'object' => $owner['url'],
2027 'published' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
2028 'instrument' => self::getService(),
2029 'to' => [ActivityPub::PUBLIC_COLLECTION],
2032 $signed = LDSignature::sign($data, $owner);
2034 Logger::info('Deliver profile deletion for user ' . $owner['uid'] . ' to ' . $inbox . ' via ActivityPub');
2035 return HTTPSignature::transmit($signed, $inbox, $owner);
2039 * Transmits a profile change to a given inbox
2041 * @param array $owner Sender owner-view record
2042 * @param string $inbox Target inbox
2043 * @return boolean was the transmission successful?
2044 * @throws HTTPException\InternalServerErrorException
2045 * @throws HTTPException\NotFoundException
2046 * @throws \ImagickException
2048 public static function sendProfileUpdate(array $owner, string $inbox): bool
2050 $profile = APContact::getByURL($owner['url']);
2052 $data = ['@context' => ActivityPub::CONTEXT,
2053 'id' => DI::baseUrl() . '/activity/' . System::createGUID(),
2055 'actor' => $owner['url'],
2056 'object' => self::getProfile($owner['uid']),
2057 'published' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
2058 'instrument' => self::getService(),
2059 'to' => [$profile['followers']],
2062 $signed = LDSignature::sign($data, $owner);
2064 Logger::info('Deliver profile update for user ' . $owner['uid'] . ' to ' . $inbox . ' via ActivityPub');
2065 return HTTPSignature::transmit($signed, $inbox, $owner);
2069 * Transmits a given activity to a target
2071 * @param string $activity Type name
2072 * @param string $target Target profile
2073 * @param integer $uid User ID
2074 * @param string $id Activity-identifier
2076 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2077 * @throws \ImagickException
2078 * @throws \Exception
2080 public static function sendActivity(string $activity, string $target, int $uid, string $id = ''): bool
2082 $profile = APContact::getByURL($target);
2083 if (empty($profile['inbox'])) {
2084 Logger::warning('No inbox found for target', ['target' => $target, 'profile' => $profile]);
2088 $owner = User::getOwnerDataById($uid);
2089 if (empty($owner)) {
2090 Logger::warning('No user found for actor, aborting', ['uid' => $uid]);
2095 $id = DI::baseUrl() . '/activity/' . System::createGUID();
2099 '@context' => ActivityPub::CONTEXT,
2101 'type' => $activity,
2102 'actor' => $owner['url'],
2103 'object' => $profile['url'],
2104 'instrument' => self::getService(),
2105 'to' => [$profile['url']],
2108 Logger::info('Sending activity ' . $activity . ' to ' . $target . ' for user ' . $uid);
2110 $signed = LDSignature::sign($data, $owner);
2111 return HTTPSignature::transmit($signed, $profile['inbox'], $owner);
2115 * Transmits a "follow object" activity to a target
2116 * This is a preparation for sending automated "follow" requests when receiving "Announce" messages
2118 * @param string $object Object URL
2119 * @param string $target Target profile
2120 * @param integer $uid User ID
2122 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2123 * @throws \ImagickException
2124 * @throws \Exception
2126 public static function sendFollowObject(string $object, string $target, int $uid = 0): bool
2128 $profile = APContact::getByURL($target);
2129 if (empty($profile['inbox'])) {
2130 Logger::warning('No inbox found for target', ['target' => $target, 'profile' => $profile]);
2135 // We need to use some user as a sender. It doesn't care who it will send. We will use an administrator account.
2136 $admin = User::getFirstAdmin(['uid']);
2138 Logger::warning('No available admin user for transmission', ['target' => $target]);
2142 $uid = $admin['uid'];
2145 $condition = ['verb' => Activity::FOLLOW, 'uid' => 0, 'parent-uri' => $object,
2146 'author-id' => Contact::getPublicIdByUserId($uid)];
2147 if (Post::exists($condition)) {
2148 Logger::info('Follow for ' . $object . ' for user ' . $uid . ' does already exist.');
2152 $owner = User::getOwnerDataById($uid);
2155 '@context' => ActivityPub::CONTEXT,
2156 'id' => DI::baseUrl() . '/activity/' . System::createGUID(),
2158 'actor' => $owner['url'],
2159 'object' => $object,
2160 'instrument' => self::getService(),
2161 'to' => [$profile['url']],
2164 Logger::info('Sending follow ' . $object . ' to ' . $target . ' for user ' . $uid);
2166 $signed = LDSignature::sign($data, $owner);
2167 return HTTPSignature::transmit($signed, $profile['inbox'], $owner);
2171 * Transmit a message that the contact request had been accepted
2173 * @param string $target Target profile
2174 * @param string $id Object id
2175 * @param integer $uid User ID
2177 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2178 * @throws \ImagickException
2180 public static function sendContactAccept(string $target, string $id, int $uid)
2182 $profile = APContact::getByURL($target);
2183 if (empty($profile['inbox'])) {
2184 Logger::warning('No inbox found for target', ['target' => $target, 'profile' => $profile]);
2188 $owner = User::getOwnerDataById($uid);
2190 Logger::notice('No user found for actor', ['uid' => $uid]);
2195 '@context' => ActivityPub::CONTEXT,
2196 'id' => DI::baseUrl() . '/activity/' . System::createGUID(),
2198 'actor' => $owner['url'],
2202 'actor' => $profile['url'],
2203 'object' => $owner['url']
2205 'instrument' => self::getService(),
2206 'to' => [$profile['url']],
2209 Logger::debug('Sending accept to ' . $target . ' for user ' . $uid . ' with id ' . $id);
2211 $signed = LDSignature::sign($data, $owner);
2212 HTTPSignature::transmit($signed, $profile['inbox'], $owner);
2216 * Reject a contact request or terminates the contact relation
2218 * @param string $target Target profile
2219 * @param string $objectId Object id
2220 * @param array $owner Sender owner-view record
2221 * @return bool Operation success
2222 * @throws HTTPException\InternalServerErrorException
2223 * @throws \ImagickException
2225 public static function sendContactReject(string $target, string $objectId, array $owner): bool
2227 $profile = APContact::getByURL($target);
2228 if (empty($profile['inbox'])) {
2229 Logger::warning('No inbox found for target', ['target' => $target, 'profile' => $profile]);
2234 '@context' => ActivityPub::CONTEXT,
2235 'id' => DI::baseUrl() . '/activity/' . System::createGUID(),
2237 'actor' => $owner['url'],
2241 'actor' => $profile['url'],
2242 'object' => $owner['url']
2244 'instrument' => self::getService(),
2245 'to' => [$profile['url']],
2248 Logger::debug('Sending reject to ' . $target . ' for user ' . $owner['uid'] . ' with id ' . $objectId);
2250 $signed = LDSignature::sign($data, $owner);
2251 return HTTPSignature::transmit($signed, $profile['inbox'], $owner);
2255 * Transmits a message that we don't want to follow this contact anymore
2257 * @param string $target Target profile
2258 * @param integer $cid Contact id
2259 * @param array $owner Sender owner-view record
2260 * @return bool success
2261 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2262 * @throws \ImagickException
2263 * @throws \Exception
2265 public static function sendContactUndo(string $target, int $cid, array $owner): bool
2267 $profile = APContact::getByURL($target);
2268 if (empty($profile['inbox'])) {
2269 Logger::warning('No inbox found for target', ['target' => $target, 'profile' => $profile]);
2273 $object_id = self::activityIDFromContact($cid);
2274 if (empty($object_id)) {
2278 $objectId = DI::baseUrl() . '/activity/' . System::createGUID();
2281 '@context' => ActivityPub::CONTEXT,
2284 'actor' => $owner['url'],
2288 'actor' => $owner['url'],
2289 'object' => $profile['url']
2291 'instrument' => self::getService(),
2292 'to' => [$profile['url']],
2295 Logger::info('Sending undo to ' . $target . ' for user ' . $owner['uid'] . ' with id ' . $objectId);
2297 $signed = LDSignature::sign($data, $owner);
2298 return HTTPSignature::transmit($signed, $profile['inbox'], $owner);
2302 * Prepends mentions (@) to $body variable
2304 * @param string $body HTML code
2306 * @param string $authorLink Author link
2307 * @return string HTML code with prepended mentions
2309 private static function prependMentions(string $body, int $uriid, string $authorLink): string
2313 foreach (Tag::getByURIId($uriid, [Tag::IMPLICIT_MENTION]) as $tag) {
2314 $profile = Contact::getByURL($tag['url'], false, ['addr', 'contact-type', 'nick']);
2315 if (!empty($profile['addr'])
2316 && $profile['contact-type'] != Contact::TYPE_COMMUNITY
2317 && !strstr($body, $profile['addr'])
2318 && !strstr($body, $tag['url'])
2319 && $tag['url'] !== $authorLink
2321 $mentions[] = '@[url=' . $tag['url'] . ']' . $profile['nick'] . '[/url]';
2325 $mentions[] = $body;
2327 return implode(' ', $mentions);