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:';
66 * Add relay servers to the list of inboxes
68 * @param array $inboxes
69 * @return array inboxes with added relay servers
71 public static function addRelayServerInboxes(array $inboxes = [])
73 foreach (Relay::getList(['inbox']) as $contact) {
74 $inboxes[$contact['inbox']] = $contact['inbox'];
81 * Add relay servers to the list of inboxes
83 * @param array $inboxes
84 * @return array inboxes with added relay servers
86 public static function addRelayServerInboxesForItem(int $item_id, array $inboxes = [])
88 $item = Post::selectFirst(['uid'], ['id' => $item_id]);
93 $relays = Relay::getDirectRelayList($item_id);
98 foreach ($relays as $relay) {
99 $contact = Contact::getByURLForUser($relay['url'], $item['uid'], false, ['id']);
100 $inboxes[$relay['batch']][] = $contact['id'] ?? 0;
106 * Subscribe to a relay
108 * @param string $url Subscribe actor url
109 * @return bool success
111 public static function sendRelayFollow(string $url)
113 $contact = Contact::getByURL($url);
114 if (empty($contact)) {
118 $activity_id = ActivityPub\Transmitter::activityIDFromContact($contact['id']);
119 $success = ActivityPub\Transmitter::sendActivity('Follow', $url, 0, $activity_id);
121 Contact::update(['rel' => Contact::FRIEND], ['id' => $contact['id']]);
128 * Unsubscribe from a relay
130 * @param string $url Subscribe actor url
131 * @param bool $force Set the relay status as non follower even if unsubscribe hadn't worked
132 * @return bool success
134 public static function sendRelayUndoFollow(string $url, bool $force = false)
136 $contact = Contact::getByURL($url);
137 if (empty($contact)) {
141 $success = self::sendContactUndo($url, $contact['id'], 0);
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
159 * @return array of owners
162 public static function getContacts(array $owner, array $rel, string $module, int $page = null, string $requester = null, $nocache = false)
165 $cachekey = self::CACHEKEY_CONTACTS . $module . ':'. $owner['uid'];
166 $result = DI::cache()->get($cachekey);
167 if (!$nocache && !is_null($result)) {
174 'uid' => $owner['uid'],
183 $condition = DBA::mergeConditions($parameters, ["`url` IN (SELECT `url` FROM `apcontact`)"]);
185 $total = DBA::count('contact', $condition);
187 $modulePath = '/' . $module . '/';
189 $data = ['@context' => ActivityPub::CONTEXT];
190 $data['id'] = DI::baseUrl() . $modulePath . $owner['nickname'];
191 $data['type'] = 'OrderedCollection';
192 $data['totalItems'] = $total;
195 $data['id'] .= '?' . http_build_query(['page' => $page]);
198 // When we hide our friends we will only show the pure number but don't allow more.
199 $show_contacts = empty($owner['hide-friends']);
201 // Allow fetching the contact list when the requester is part of the list.
202 if (($owner['page-flags'] == User::PAGE_FLAGS_PRVGROUP) && !empty($requester)) {
203 $show_contacts = DBA::exists('contact', ['nurl' => Strings::normaliseLink($requester), 'uid' => $owner['uid'], 'blocked' => false]);
206 if (!$show_contacts) {
207 if (!empty($cachekey)) {
208 DI::cache()->set($cachekey, $data, Duration::DAY);
215 $data['first'] = DI::baseUrl() . $modulePath . $owner['nickname'] . '?page=1';
217 $data['type'] = 'OrderedCollectionPage';
220 $contacts = DBA::select('contact', ['url'], $condition, ['limit' => [($page - 1) * 100, 100]]);
221 while ($contact = DBA::fetch($contacts)) {
222 $list[] = $contact['url'];
224 DBA::close($contacts);
226 if (count($list) == 100) {
227 $data['next'] = DI::baseUrl() . $modulePath . $owner['nickname'] . '?page=' . ($page + 1);
230 $data['partOf'] = DI::baseUrl() . $modulePath . $owner['nickname'];
232 $data['orderedItems'] = $list;
235 if (!empty($cachekey)) {
236 DI::cache()->set($cachekey, $data, Duration::DAY);
243 * Public posts for the given owner
245 * @param array $owner Owner array
246 * @param integer $page Page number
247 * @param string $requester URL of requesting account
248 * @param boolean $nocache Wether to bypass caching
250 * @return array of posts
251 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
252 * @throws \ImagickException
254 public static function getOutbox(array $owner, int $page = null, string $requester = '', $nocache = false)
257 $cachekey = self::CACHEKEY_OUTBOX . $owner['uid'];
258 $result = DI::cache()->get($cachekey);
259 if (!$nocache && !is_null($result)) {
264 $condition = ['private' => [Item::PUBLIC, Item::UNLISTED]];
266 if (!empty($requester)) {
267 $requester_id = Contact::getIdForURL($requester, $owner['uid']);
268 if (!empty($requester_id)) {
269 $permissionSets = DI::permissionSet()->selectByContactId($requester_id, $owner['uid']);
270 if (!empty($permissionSets)) {
271 $condition = ['psid' => array_merge($permissionSets->column('id'),
272 [DI::permissionSet()->selectPublicForUser($owner['uid'])])];
277 $condition = array_merge($condition,
278 ['uid' => $owner['uid'],
279 'author-id' => Contact::getIdForURL($owner['url'], 0, false),
280 'gravity' => [GRAVITY_PARENT, GRAVITY_COMMENT],
281 'network' => Protocol::FEDERATED,
282 'parent-network' => Protocol::FEDERATED,
287 $count = Post::count($condition);
289 $data = ['@context' => ActivityPub::CONTEXT];
290 $data['id'] = DI::baseUrl() . '/outbox/' . $owner['nickname'];
291 $data['type'] = 'OrderedCollection';
292 $data['totalItems'] = $count;
295 $data['id'] .= '?' . http_build_query(['page' => $page]);
299 $data['first'] = DI::baseUrl() . '/outbox/' . $owner['nickname'] . '?page=1';
301 $data['type'] = 'OrderedCollectionPage';
304 $items = Post::select(['id'], $condition, ['limit' => [($page - 1) * 20, 20], 'order' => ['created' => true]]);
305 while ($item = Post::fetch($items)) {
306 $activity = self::createActivityFromItem($item['id'], true);
307 $activity['type'] = $activity['type'] == 'Update' ? 'Create' : $activity['type'];
309 // Only list "Create" activity objects here, no reshares
310 if (!empty($activity['object']) && ($activity['type'] == 'Create')) {
311 $list[] = $activity['object'];
316 if (count($list) == 20) {
317 $data['next'] = DI::baseUrl() . '/outbox/' . $owner['nickname'] . '?page=' . ($page + 1);
320 $data['partOf'] = DI::baseUrl() . '/outbox/' . $owner['nickname'];
322 $data['orderedItems'] = $list;
325 if (!empty($cachekey)) {
326 DI::cache()->set($cachekey, $data, Duration::DAY);
333 * Public posts for the given owner
335 * @param array $owner Owner array
336 * @param integer $page Page number
337 * @param boolean $nocache Wether to bypass caching
339 * @return array of posts
340 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
341 * @throws \ImagickException
343 public static function getFeatured(array $owner, int $page = null, $nocache = false)
346 $cachekey = self::CACHEKEY_FEATURED . $owner['uid'];
347 $result = DI::cache()->get($cachekey);
348 if (!$nocache && !is_null($result)) {
353 $owner_cid = Contact::getIdForURL($owner['url'], 0, false);
355 $condition = ["`uri-id` IN (SELECT `uri-id` FROM `collection-view` WHERE `cid` = ? AND `type` = ?)",
356 $owner_cid, Post\Collection::FEATURED];
358 $condition = DBA::mergeConditions($condition,
359 ['uid' => $owner['uid'],
360 'author-id' => $owner_cid,
361 'private' => [Item::PUBLIC, Item::UNLISTED],
362 'gravity' => [GRAVITY_PARENT, GRAVITY_COMMENT],
363 'network' => Protocol::FEDERATED,
364 'parent-network' => Protocol::FEDERATED,
369 $count = Post::count($condition);
371 $data = ['@context' => ActivityPub::CONTEXT];
372 $data['id'] = DI::baseUrl() . '/featured/' . $owner['nickname'];
373 $data['type'] = 'OrderedCollection';
374 $data['totalItems'] = $count;
377 $data['id'] .= '?' . http_build_query(['page' => $page]);
381 $items = Post::select(['id'], $condition, ['limit' => 20, 'order' => ['created' => true]]);
383 $data['type'] = 'OrderedCollectionPage';
384 $items = Post::select(['id'], $condition, ['limit' => [($page - 1) * 20, 20], 'order' => ['created' => true]]);
388 while ($item = Post::fetch($items)) {
389 $activity = self::createActivityFromItem($item['id'], true);
390 $activity['type'] = $activity['type'] == 'Update' ? 'Create' : $activity['type'];
392 // Only list "Create" activity objects here, no reshares
393 if (!empty($activity['object']) && ($activity['type'] == 'Create')) {
394 $list[] = $activity['object'];
399 if (count($list) == 20) {
400 $data['next'] = DI::baseUrl() . '/featured/' . $owner['nickname'] . '?page=' . ($page + 1);
404 $data['partOf'] = DI::baseUrl() . '/featured/' . $owner['nickname'];
407 $data['orderedItems'] = $list;
409 if (!empty($cachekey)) {
410 DI::cache()->set($cachekey, $data, Duration::DAY);
417 * Return the service array containing information the used software and it's url
419 * @return array with service data
421 private static function getService()
423 return ['type' => 'Service',
424 'name' => FRIENDICA_PLATFORM . " '" . FRIENDICA_CODENAME . "' " . FRIENDICA_VERSION . '-' . DB_UPDATE_VERSION,
425 'url' => DI::baseUrl()->get()];
429 * Return the ActivityPub profile of the given user
431 * @param int $uid User ID
432 * @return array with profile data
433 * @throws HTTPException\NotFoundException
434 * @throws HTTPException\InternalServerErrorException
436 public static function getProfile(int $uid): array
438 $owner = User::getOwnerDataById($uid);
439 if (!isset($owner['id'])) {
440 DI::logger()->error('Unable to find owner data for uid', ['uid' => $uid, 'callstack' => System::callstack(20)]);
441 throw new HTTPException\NotFoundException('User not found.');
444 $data = ['@context' => ActivityPub::CONTEXT];
445 $data['id'] = $owner['url'];
447 if (!empty($owner['guid'])) {
448 $data['diaspora:guid'] = $owner['guid'];
451 $data['type'] = ActivityPub::ACCOUNT_TYPES[$owner['account-type']];
454 $data['following'] = DI::baseUrl() . '/following/' . $owner['nick'];
455 $data['followers'] = DI::baseUrl() . '/followers/' . $owner['nick'];
456 $data['inbox'] = DI::baseUrl() . '/inbox/' . $owner['nick'];
457 $data['outbox'] = DI::baseUrl() . '/outbox/' . $owner['nick'];
458 $data['featured'] = DI::baseUrl() . '/featured/' . $owner['nick'];
460 $data['inbox'] = DI::baseUrl() . '/friendica/inbox';
463 $data['preferredUsername'] = $owner['nick'];
464 $data['name'] = $owner['name'];
466 if (!empty($owner['country-name'] . $owner['region'] . $owner['locality'])) {
467 $data['vcard:hasAddress'] = ['@type' => 'vcard:Home', 'vcard:country-name' => $owner['country-name'],
468 'vcard:region' => $owner['region'], 'vcard:locality' => $owner['locality']];
471 if (!empty($owner['about'])) {
472 $data['summary'] = BBCode::convertForUriId($owner['uri-id'] ?? 0, $owner['about'], BBCode::EXTERNAL);
475 if (!empty($owner['xmpp']) || !empty($owner['matrix'])) {
476 $data['vcard:hasInstantMessage'] = [];
478 if (!empty($owner['xmpp'])) {
479 $data['vcard:hasInstantMessage'][] = 'xmpp:' . $owner['xmpp'];
481 if (!empty($owner['matrix'])) {
482 $data['vcard:hasInstantMessage'][] = 'matrix:' . $owner['matrix'];
486 $data['url'] = $owner['url'];
487 $data['manuallyApprovesFollowers'] = in_array($owner['page-flags'], [User::PAGE_FLAGS_NORMAL, User::PAGE_FLAGS_PRVGROUP]);
488 $data['discoverable'] = (bool)$owner['net-publish'];
489 $data['publicKey'] = ['id' => $owner['url'] . '#main-key',
490 'owner' => $owner['url'],
491 'publicKeyPem' => $owner['pubkey']];
492 $data['endpoints'] = ['sharedInbox' => DI::baseUrl() . '/inbox'];
493 $data['icon'] = ['type' => 'Image', 'url' => User::getAvatarUrl($owner)];
495 $resourceid = Photo::ridFromURI($owner['photo']);
496 if (!empty($resourceid)) {
497 $photo = Photo::selectFirst(['type'], ["resource-id" => $resourceid]);
498 if (!empty($photo['type'])) {
499 $data['icon']['mediaType'] = $photo['type'];
503 if (!empty($owner['header'])) {
504 $data['image'] = ['type' => 'Image', 'url' => Contact::getHeaderUrlForId($owner['id'], '', $owner['updated'])];
506 $resourceid = Photo::ridFromURI($owner['header']);
507 if (!empty($resourceid)) {
508 $photo = Photo::selectFirst(['type'], ["resource-id" => $resourceid]);
509 if (!empty($photo['type'])) {
510 $data['image']['mediaType'] = $photo['type'];
517 foreach (DI::profileField()->selectByContactId(0, $uid) as $profile_field) {
519 'type' => 'PropertyValue',
520 'name' => $profile_field->label,
521 'value' => BBCode::convertForUriId($owner['uri-id'], $profile_field->value)
525 if (!empty($custom_fields)) {
526 $data['attachment'] = $custom_fields;
529 $data['generator'] = self::getService();
531 // tags: https://kitty.town/@inmysocks/100656097926961126.json
536 * @param string $username
538 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
540 public static function getDeletedUser($username)
543 '@context' => ActivityPub::CONTEXT,
544 'id' => DI::baseUrl() . '/profile/' . $username,
545 'type' => 'Tombstone',
546 'published' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
547 'updated' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
548 'deleted' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
553 * Returns an array with permissions of the thread parent of the given item array
556 * @param bool $is_forum_thread
558 * @return array with permissions
559 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
560 * @throws \ImagickException
562 private static function fetchPermissionBlockFromThreadParent(array $item, bool $is_forum_thread)
564 if (empty($item['thr-parent-id'])) {
568 $parent = Post::selectFirstPost(['author-link'], ['uri-id' => $item['thr-parent-id']]);
569 if (empty($parent)) {
574 'to' => [$parent['author-link']],
580 $parent_profile = APContact::getByURL($parent['author-link']);
582 $item_profile = APContact::getByURL($item['author-link']);
583 $exclude[] = $item['author-link'];
585 if ($item['gravity'] == GRAVITY_PARENT) {
586 $exclude[] = $item['owner-link'];
589 $type = [Tag::TO => 'to', Tag::CC => 'cc', Tag::BTO => 'bto', Tag::BCC => 'bcc'];
590 foreach (Tag::getByURIId($item['thr-parent-id'], [Tag::TO, Tag::CC, Tag::BTO, Tag::BCC]) as $receiver) {
591 if (!empty($parent_profile['followers']) && $receiver['url'] == $parent_profile['followers'] && !empty($item_profile['followers'])) {
592 if (!$is_forum_thread) {
593 $permissions[$type[$receiver['type']]][] = $item_profile['followers'];
595 } elseif (!in_array($receiver['url'], $exclude)) {
596 $permissions[$type[$receiver['type']]][] = $receiver['url'];
604 * Check if the given item id is from ActivityPub
606 * @param integer $item_id
607 * @return boolean "true" if the post is from ActivityPub
609 private static function isAPPost(int $item_id)
611 if (empty($item_id)) {
615 return Post::exists(['id' => $item_id, 'network' => Protocol::ACTIVITYPUB]);
619 * Creates an array of permissions from an item thread
621 * @param array $item Item array
622 * @param boolean $blindcopy addressing via "bcc" or "cc"?
623 * @param integer $last_id Last item id for adding receivers
625 * @return array with permission data
626 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
627 * @throws \ImagickException
629 private static function createPermissionBlockForItem($item, $blindcopy, $last_id = 0)
632 $last_id = $item['id'];
639 // Check if we should always deliver our stuff via BCC
640 if (!empty($item['uid'])) {
641 $owner = User::getOwnerDataById($item['uid']);
642 if (!empty($owner)) {
643 $always_bcc = $owner['hide-friends'];
644 $is_forum = ($owner['account-type'] == User::ACCOUNT_TYPE_COMMUNITY) && $owner['manually-approve'];
646 $profile = APContact::getByURL($owner['url'], false);
647 $follower = $profile['followers'] ?? '';
651 if (DI::config()->get('system', 'ap_always_bcc')) {
655 $parent = Post::selectFirst(['causer-link', 'post-reason'], ['id' => $item['parent']]);
656 if (($parent['post-reason'] == Item::PR_ANNOUNCEMENT) && !empty($parent['causer-link'])) {
657 $profile = APContact::getByURL($parent['causer-link'], false);
658 $is_forum_thread = isset($profile['type']) && $profile['type'] == 'Group';
660 $is_forum_thread = false;
663 if (self::isAnnounce($item) || DI::config()->get('debug', 'total_ap_delivery') || self::isAPPost($last_id)) {
664 // Will be activated in a later step
665 $networks = Protocol::FEDERATED;
667 // For now only send to these contacts:
668 $networks = [Protocol::ACTIVITYPUB, Protocol::OSTATUS];
671 $data = ['to' => [], 'cc' => [], 'bcc' => []];
673 if ($item['gravity'] == GRAVITY_PARENT) {
674 $actor_profile = APContact::getByURL($item['owner-link']);
676 $actor_profile = APContact::getByURL($item['author-link']);
681 $terms = Tag::getByURIId($item['uri-id'], [Tag::MENTION, Tag::IMPLICIT_MENTION, Tag::EXCLUSIVE_MENTION]);
683 if ($item['private'] != Item::PRIVATE) {
684 // Directly mention the original author upon a quoted reshare.
685 // Else just ensure that the original author receives the reshare.
686 $announce = self::getAnnounceArray($item);
687 if (!empty($announce['comment'])) {
688 $data['to'][] = $announce['actor']['url'];
689 } elseif (!empty($announce)) {
690 $data['cc'][] = $announce['actor']['url'];
693 $data = array_merge($data, self::fetchPermissionBlockFromThreadParent($item, $is_forum_thread));
695 // Check if the item is completely public or unlisted
696 if ($item['private'] == Item::PUBLIC) {
697 $data['to'][] = ActivityPub::PUBLIC_COLLECTION;
699 $data['cc'][] = ActivityPub::PUBLIC_COLLECTION;
702 foreach ($terms as $term) {
703 $profile = APContact::getByURL($term['url'], false);
704 if (!empty($profile)) {
705 if ($term['type'] == Tag::EXCLUSIVE_MENTION) {
707 if (!empty($profile['followers']) && ($profile['type'] == 'Group')) {
708 $data['cc'][] = $profile['followers'];
711 $data['to'][] = $profile['url'];
715 $receiver_list = Item::enumeratePermissions($item, true);
717 foreach ($terms as $term) {
718 $cid = Contact::getIdForURL($term['url'], $item['uid']);
719 if (!empty($cid) && in_array($cid, $receiver_list)) {
720 $contact = DBA::selectFirst('contact', ['url', 'network', 'protocol', 'gsid'], ['id' => $cid, 'network' => Protocol::FEDERATED]);
721 if (!DBA::isResult($contact) || !self::isAPContact($contact, $networks)) {
725 $profile = APContact::getByURL($term['url'], false);
726 if (!empty($profile)) {
727 if ($term['type'] == Tag::EXCLUSIVE_MENTION) {
729 if (!empty($profile['followers']) && ($profile['type'] == 'Group')) {
730 $data['cc'][] = $profile['followers'];
733 $data['to'][] = $profile['url'];
738 if ($is_forum && !$exclusive && !empty($follower)) {
739 $data['cc'][] = $follower;
740 } elseif (!$exclusive) {
741 foreach ($receiver_list as $receiver) {
742 $contact = DBA::selectFirst('contact', ['url', 'hidden', 'network', 'protocol', 'gsid'], ['id' => $receiver, 'network' => Protocol::FEDERATED]);
743 if (!DBA::isResult($contact) || !self::isAPContact($contact, $networks)) {
747 if (!empty($profile = APContact::getByURL($contact['url'], false))) {
748 if ($contact['hidden'] || $always_bcc) {
749 $data['bcc'][] = $profile['url'];
751 $data['cc'][] = $profile['url'];
758 if (!empty($item['parent'])) {
759 $parents = Post::select(['id', 'author-link', 'owner-link', 'gravity', 'uri'], ['parent' => $item['parent']], ['order' => ['id']]);
760 while ($parent = Post::fetch($parents)) {
761 if ($parent['gravity'] == GRAVITY_PARENT) {
762 $profile = APContact::getByURL($parent['owner-link'], false);
763 if (!empty($profile)) {
764 if ($item['gravity'] != GRAVITY_PARENT) {
765 // Comments to forums are directed to the forum
766 // But comments to forums aren't directed to the followers collection
767 // This rule is only valid when the actor isn't the forum.
768 // The forum needs to transmit their content to their followers.
769 if (($profile['type'] == 'Group') && ($profile['url'] != ($actor_profile['url'] ?? ''))) {
770 $data['to'][] = $profile['url'];
772 $data['cc'][] = $profile['url'];
773 if (($item['private'] != Item::PRIVATE) && !empty($actor_profile['followers'])&& !$is_forum_thread) {
774 $data['cc'][] = $actor_profile['followers'];
777 } elseif (!$exclusive && !$is_forum_thread) {
778 // Public thread parent post always are directed to the followers.
779 if ($item['private'] != Item::PRIVATE) {
780 $data['cc'][] = $actor_profile['followers'];
786 // Don't include data from future posts
787 if ($parent['id'] >= $last_id) {
791 $profile = APContact::getByURL($parent['author-link'], false);
792 if (!empty($profile)) {
793 if (($profile['type'] == 'Group') || ($parent['uri'] == $item['thr-parent'])) {
794 $data['to'][] = $profile['url'];
796 $data['cc'][] = $profile['url'];
800 DBA::close($parents);
803 $data['to'] = array_unique($data['to']);
804 $data['cc'] = array_unique($data['cc']);
805 $data['bcc'] = array_unique($data['bcc']);
807 if (($key = array_search($item['author-link'], $data['to'])) !== false) {
808 unset($data['to'][$key]);
811 if (($key = array_search($item['author-link'], $data['cc'])) !== false) {
812 unset($data['cc'][$key]);
815 if (($key = array_search($item['author-link'], $data['bcc'])) !== false) {
816 unset($data['bcc'][$key]);
819 foreach ($data['to'] as $to) {
820 if (($key = array_search($to, $data['cc'])) !== false) {
821 unset($data['cc'][$key]);
824 if (($key = array_search($to, $data['bcc'])) !== false) {
825 unset($data['bcc'][$key]);
829 foreach ($data['cc'] as $cc) {
830 if (($key = array_search($cc, $data['bcc'])) !== false) {
831 unset($data['bcc'][$key]);
835 $receivers = ['to' => array_values($data['to']), 'cc' => array_values($data['cc']), 'bcc' => array_values($data['bcc'])];
838 unset($receivers['bcc']);
841 foreach (['to' => Tag::TO, 'cc' => Tag::CC, 'bcc' => Tag::BCC] as $element => $type) {
842 if (!empty($receivers[$element])) {
843 foreach ($receivers[$element] as $receiver) {
844 if ($receiver == ActivityPub::PUBLIC_COLLECTION) {
845 $name = Receiver::PUBLIC_COLLECTION;
847 $name = trim(parse_url($receiver, PHP_URL_PATH), '/');
849 Tag::store($item['uri-id'], $type, $name, $receiver);
858 * Check if an inbox is archived
860 * @param string $url Inbox url
862 * @return boolean "true" if inbox is archived
864 public static function archivedInbox($url)
866 return DBA::exists('inbox-status', ['url' => $url, 'archive' => true]);
870 * Check if a given contact should be delivered via AP
872 * @param array $contact
873 * @param array $networks
877 private static function isAPContact(array $contact, array $networks)
879 if (in_array($contact['network'], $networks) || ($contact['protocol'] == Protocol::ACTIVITYPUB)) {
883 return GServer::getProtocol($contact['gsid'] ?? 0) == Post\DeliveryData::ACTIVITYPUB;
887 * Fetches a list of inboxes of followers of a given user
889 * @param integer $uid User ID
890 * @param boolean $personal fetch personal inboxes
891 * @param boolean $all_ap Retrieve all AP enabled inboxes
893 * @return array of follower inboxes
894 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
895 * @throws \ImagickException
897 public static function fetchTargetInboxesforUser($uid, $personal = false, bool $all_ap = false)
903 if (!empty($item['uid'])) {
904 $profile = User::getOwnerDataById($item['uid']);
905 if (!empty($profile)) {
906 $isforum = $profile['account-type'] == User::ACCOUNT_TYPE_COMMUNITY;
910 if (DI::config()->get('debug', 'total_ap_delivery') || $all_ap) {
911 // Will be activated in a later step
912 $networks = Protocol::FEDERATED;
914 // For now only send to these contacts:
915 $networks = [Protocol::ACTIVITYPUB, Protocol::OSTATUS];
918 $condition = ['uid' => $uid, 'archive' => false, 'pending' => false, 'blocked' => false, 'network' => Protocol::FEDERATED];
921 $condition['rel'] = [Contact::FOLLOWER, Contact::FRIEND];
924 $contacts = DBA::select('contact', ['id', 'url', 'network', 'protocol', 'gsid'], $condition);
925 while ($contact = DBA::fetch($contacts)) {
926 if (!self::isAPContact($contact, $networks)) {
930 if ($isforum && ($contact['network'] == Protocol::DFRN)) {
934 if (Network::isUrlBlocked($contact['url'])) {
938 $profile = APContact::getByURL($contact['url'], false);
939 if (!empty($profile)) {
940 if (empty($profile['sharedinbox']) || $personal || Contact::isLocal($contact['url'])) {
941 $target = $profile['inbox'];
943 $target = $profile['sharedinbox'];
945 if (!self::archivedInbox($target)) {
946 $inboxes[$target][] = $contact['id'];
950 DBA::close($contacts);
956 * Fetches an array of inboxes for the given item and user
958 * @param array $item Item array
959 * @param integer $uid User ID
960 * @param boolean $personal fetch personal inboxes
961 * @param integer $last_id Last item id for adding receivers
962 * @return array with inboxes
963 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
964 * @throws \ImagickException
966 public static function fetchTargetInboxes($item, $uid, $personal = false, $last_id = 0)
968 $permissions = self::createPermissionBlockForItem($item, true, $last_id);
969 if (empty($permissions)) {
975 if ($item['gravity'] == GRAVITY_ACTIVITY) {
976 $item_profile = APContact::getByURL($item['author-link'], false);
978 $item_profile = APContact::getByURL($item['owner-link'], false);
981 if (empty($item_profile)) {
985 $profile_uid = User::getIdForURL($item_profile['url']);
987 foreach (['to', 'cc', 'bto', 'bcc'] as $element) {
988 if (empty($permissions[$element])) {
992 $blindcopy = in_array($element, ['bto', 'bcc']);
994 foreach ($permissions[$element] as $receiver) {
995 if (empty($receiver) || Network::isUrlBlocked($receiver)) {
999 if ($item_profile && ($receiver == $item_profile['followers']) && ($uid == $profile_uid)) {
1000 $inboxes = array_merge($inboxes, self::fetchTargetInboxesforUser($uid, $personal, self::isAPPost($last_id)));
1002 $profile = APContact::getByURL($receiver, false);
1003 if (!empty($profile)) {
1004 $contact = Contact::getByURLForUser($receiver, $uid, false, ['id']);
1006 if (empty($profile['sharedinbox']) || $personal || $blindcopy || Contact::isLocal($receiver)) {
1007 $target = $profile['inbox'];
1009 $target = $profile['sharedinbox'];
1011 if (!self::archivedInbox($target)) {
1012 $inboxes[$target][] = $contact['id'] ?? 0;
1023 * Creates an array in the structure of the item table for a given mail id
1025 * @param integer $mail_id
1028 * @throws \Exception
1030 public static function ItemArrayFromMail($mail_id, $use_title = false)
1032 $mail = DBA::selectFirst('mail', [], ['id' => $mail_id]);
1033 if (!DBA::isResult($mail)) {
1037 $reply = DBA::selectFirst('mail', ['uri', 'uri-id', 'from-url'], ['parent-uri' => $mail['parent-uri'], 'reply' => false]);
1038 if (!DBA::isResult($reply)) {
1042 // Making the post more compatible for Mastodon by:
1043 // - Making it a note and not an article (no title)
1044 // - Moving the title into the "summary" field that is used as a "content warning"
1047 $mail['body'] = '[abstract]' . $mail['title'] . "[/abstract]\n" . $mail['body'];
1048 $mail['title'] = '';
1051 $mail['content-warning'] = '';
1052 $mail['author-link'] = $mail['owner-link'] = $mail['from-url'];
1053 $mail['owner-id'] = $mail['author-id'];
1054 $mail['allow_cid'] = '<'.$mail['contact-id'].'>';
1055 $mail['allow_gid'] = '';
1056 $mail['deny_cid'] = '';
1057 $mail['deny_gid'] = '';
1058 $mail['private'] = Item::PRIVATE;
1059 $mail['deleted'] = false;
1060 $mail['edited'] = $mail['created'];
1061 $mail['plink'] = DI::baseUrl() . '/message/' . $mail['id'];
1062 $mail['parent-uri'] = $reply['uri'];
1063 $mail['parent-uri-id'] = $reply['uri-id'];
1064 $mail['parent-author-id'] = Contact::getIdForURL($reply['from-url'], 0, false);
1065 $mail['gravity'] = ($mail['reply'] ? GRAVITY_COMMENT: GRAVITY_PARENT);
1066 $mail['event-type'] = '';
1067 $mail['language'] = '';
1068 $mail['parent'] = 0;
1074 * Creates an activity array for a given mail id
1076 * @param integer $mail_id
1077 * @param boolean $object_mode Is the activity item is used inside another object?
1079 * @return array of activity
1080 * @throws \Exception
1082 public static function createActivityFromMail($mail_id, $object_mode = false)
1084 $mail = self::ItemArrayFromMail($mail_id);
1088 $object = self::createNote($mail);
1090 if (!$object_mode) {
1091 $data = ['@context' => ActivityPub::CONTEXT];
1096 $data['id'] = $mail['uri'] . '/Create';
1097 $data['type'] = 'Create';
1098 $data['actor'] = $mail['author-link'];
1099 $data['published'] = DateTimeFormat::utc($mail['created'] . '+00:00', DateTimeFormat::ATOM);
1100 $data['instrument'] = self::getService();
1101 $data = array_merge($data, self::createPermissionBlockForItem($mail, true));
1103 if (empty($data['to']) && !empty($data['cc'])) {
1104 $data['to'] = $data['cc'];
1107 if (empty($data['to']) && !empty($data['bcc'])) {
1108 $data['to'] = $data['bcc'];
1112 unset($data['bcc']);
1114 $object['to'] = $data['to'];
1115 $object['tag'] = [['type' => 'Mention', 'href' => $object['to'][0], 'name' => '']];
1117 unset($object['cc']);
1118 unset($object['bcc']);
1120 $data['directMessage'] = true;
1122 $data['object'] = $object;
1124 $owner = User::getOwnerDataById($mail['uid']);
1126 if (!$object_mode && !empty($owner)) {
1127 return LDSignature::sign($data, $owner);
1134 * Returns the activity type of a given item
1136 * @param array $item
1138 * @return string with activity type
1139 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1140 * @throws \ImagickException
1142 private static function getTypeOfItem($item)
1146 // Only check for a reshare, if it is a real reshare and no quoted reshare
1147 if (strpos($item['body'], "[share") === 0) {
1148 $announce = self::getAnnounceArray($item);
1149 $reshared = !empty($announce);
1154 } elseif ($item['verb'] == Activity::POST) {
1155 if ($item['created'] == $item['edited']) {
1160 } elseif ($item['verb'] == Activity::LIKE) {
1162 } elseif ($item['verb'] == Activity::DISLIKE) {
1164 } elseif ($item['verb'] == Activity::ATTEND) {
1166 } elseif ($item['verb'] == Activity::ATTENDNO) {
1168 } elseif ($item['verb'] == Activity::ATTENDMAYBE) {
1169 $type = 'TentativeAccept';
1170 } elseif ($item['verb'] == Activity::FOLLOW) {
1172 } elseif ($item['verb'] == Activity::TAG) {
1174 } elseif ($item['verb'] == Activity::ANNOUNCE) {
1184 * Creates the activity or fetches it from the cache
1186 * @param integer $item_id
1187 * @param boolean $force Force new cache entry
1189 * @return array with the activity
1190 * @throws \Exception
1192 public static function createCachedActivityFromItem($item_id, $force = false)
1194 $cachekey = 'APDelivery:createActivity:' . $item_id;
1197 $data = DI::cache()->get($cachekey);
1198 if (!is_null($data)) {
1203 $data = self::createActivityFromItem($item_id);
1205 DI::cache()->set($cachekey, $data, Duration::QUARTER_HOUR);
1210 * Creates an activity array for a given item id
1212 * @param integer $item_id
1213 * @param boolean $object_mode Is the activity item is used inside another object?
1215 * @return false|array
1216 * @throws \Exception
1218 public static function createActivityFromItem(int $item_id, bool $object_mode = false)
1220 Logger::info('Fetching activity', ['item' => $item_id]);
1221 $item = Post::selectFirst(Item::DELIVER_FIELDLIST, ['id' => $item_id, 'parent-network' => Protocol::NATIVE_SUPPORT]);
1222 if (!DBA::isResult($item)) {
1226 if (empty($item['uri-id'])) {
1227 Logger::warning('Item without uri-id', ['item' => $item]);
1231 if (!$item['deleted']) {
1232 $condition = ['item-uri' => $item['uri'], 'protocol' => Conversation::PARCEL_ACTIVITYPUB];
1233 $conversation = DBA::selectFirst('conversation', ['source'], $condition);
1234 if (!$item['origin'] && DBA::isResult($conversation)) {
1235 $data = json_decode($conversation['source'], true);
1236 if (!empty($data['type'])) {
1237 if (in_array($data['type'], ['Create', 'Update'])) {
1239 unset($data['@context']);
1240 unset($data['signature']);
1242 Logger::info('Return stored conversation', ['item' => $item_id]);
1244 } elseif (in_array('as:' . $data['type'], Receiver::CONTENT_TYPES)) {
1245 if (!empty($data['@context'])) {
1246 $context = $data['@context'];
1247 unset($data['@context']);
1249 unset($data['actor']);
1256 $type = self::getTypeOfItem($item);
1258 if (!$object_mode) {
1259 $data = ['@context' => $context ?? ActivityPub::CONTEXT];
1261 if ($item['deleted'] && ($item['gravity'] == GRAVITY_ACTIVITY)) {
1263 } elseif ($item['deleted']) {
1270 if ($type == 'Delete') {
1271 $data['id'] = Item::newURI($item['uid'], $item['guid']) . '/' . $type;;
1272 } elseif (($item['gravity'] == GRAVITY_ACTIVITY) && ($type != 'Undo')) {
1273 $data['id'] = $item['uri'];
1275 $data['id'] = $item['uri'] . '/' . $type;
1278 $data['type'] = $type;
1280 if (($type != 'Announce') || ($item['gravity'] != GRAVITY_PARENT)) {
1281 $data['actor'] = $item['author-link'];
1283 $data['actor'] = $item['owner-link'];
1286 $data['published'] = DateTimeFormat::utc($item['created'] . '+00:00', DateTimeFormat::ATOM);
1288 $data['instrument'] = self::getService();
1290 $data = array_merge($data, self::createPermissionBlockForItem($item, false));
1292 if (in_array($data['type'], ['Create', 'Update', 'Delete'])) {
1293 $data['object'] = $object ?? self::createNote($item);
1294 $data['published'] = DateTimeFormat::utcNow(DateTimeFormat::ATOM);
1295 } elseif ($data['type'] == 'Add') {
1296 $data = self::createAddTag($item, $data);
1297 } elseif ($data['type'] == 'Announce') {
1298 if ($item['verb'] == ACTIVITY::ANNOUNCE) {
1299 $data['object'] = $item['thr-parent'];
1301 $data = self::createAnnounce($item, $data);
1303 } elseif ($data['type'] == 'Follow') {
1304 $data['object'] = $item['parent-uri'];
1305 } elseif ($data['type'] == 'Undo') {
1306 $data['object'] = self::createActivityFromItem($item_id, true);
1308 $data['diaspora:guid'] = $item['guid'];
1309 if (!empty($item['signed_text'])) {
1310 $data['diaspora:like'] = $item['signed_text'];
1312 $data['object'] = $item['thr-parent'];
1315 if (!empty($item['contact-uid'])) {
1316 $uid = $item['contact-uid'];
1318 $uid = $item['uid'];
1321 $owner = User::getOwnerDataById($uid);
1323 Logger::info('Fetched activity', ['item' => $item_id, 'uid' => $uid]);
1325 // We don't sign if we aren't the actor. This is important for relaying content especially for forums
1326 if (!$object_mode && !empty($owner) && ($data['actor'] == $owner['url'])) {
1327 return LDSignature::sign($data, $owner);
1332 /// @todo Create "conversation" entry
1336 * Creates a location entry for a given item array
1338 * @param array $item
1340 * @return array with location array
1342 private static function createLocation($item)
1344 $location = ['type' => 'Place'];
1346 if (!empty($item['location'])) {
1347 $location['name'] = $item['location'];
1352 if (empty($item['coord'])) {
1353 $coord = Map::getCoordinates($item['location']);
1355 $coords = explode(' ', $item['coord']);
1356 if (count($coords) == 2) {
1357 $coord = ['lat' => $coords[0], 'lon' => $coords[1]];
1361 if (!empty($coord['lat']) && !empty($coord['lon'])) {
1362 $location['latitude'] = $coord['lat'];
1363 $location['longitude'] = $coord['lon'];
1370 * Returns a tag array for a given item array
1372 * @param array $item
1374 * @return array of tags
1375 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1377 private static function createTagList($item)
1381 $terms = Tag::getByURIId($item['uri-id'], [Tag::HASHTAG, Tag::MENTION, Tag::IMPLICIT_MENTION, Tag::EXCLUSIVE_MENTION]);
1382 foreach ($terms as $term) {
1383 if ($term['type'] == Tag::HASHTAG) {
1384 $url = DI::baseUrl() . '/search?tag=' . urlencode($term['name']);
1385 $tags[] = ['type' => 'Hashtag', 'href' => $url, 'name' => '#' . $term['name']];
1387 $contact = Contact::getByURL($term['url'], false, ['addr']);
1388 if (empty($contact)) {
1391 if (!empty($contact['addr'])) {
1392 $mention = '@' . $contact['addr'];
1394 $mention = '@' . $term['url'];
1397 $tags[] = ['type' => 'Mention', 'href' => $term['url'], 'name' => $mention];
1401 $announce = self::getAnnounceArray($item);
1402 // Mention the original author upon commented reshares
1403 if (!empty($announce['comment'])) {
1404 $tags[] = ['type' => 'Mention', 'href' => $announce['actor']['url'], 'name' => '@' . $announce['actor']['addr']];
1411 * Adds attachment data to the JSON document
1413 * @param array $item Data of the item that is to be posted
1414 * @param string $type Object type
1416 * @return array with attachment data
1417 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1419 private static function createAttachmentList($item, $type)
1423 $uriids = [$item['uri-id']];
1424 $shared = BBCode::fetchShareAttributes($item['body']);
1425 if (!empty($shared['guid'])) {
1426 $shared_item = Post::selectFirst(['uri-id'], ['guid' => $shared['guid']]);
1427 if (!empty($shared_item['uri-id'])) {
1428 $uriids[] = $shared_item['uri-id'];
1433 foreach ($uriids as $uriid) {
1434 foreach (Post\Media::getByURIId($uriid, [Post\Media::AUDIO, Post\Media::IMAGE, Post\Media::VIDEO, Post\Media::DOCUMENT, Post\Media::TORRENT]) as $attachment) {
1435 if (in_array($attachment['url'], $urls)) {
1438 $urls[] = $attachment['url'];
1440 $attach = ['type' => 'Document',
1441 'mediaType' => $attachment['mimetype'],
1442 'url' => $attachment['url'],
1443 'name' => $attachment['description']];
1445 if (!empty($attachment['height'])) {
1446 $attach['height'] = $attachment['height'];
1449 if (!empty($attachment['width'])) {
1450 $attach['width'] = $attachment['width'];
1453 if (!empty($attachment['preview'])) {
1454 $attach['image'] = $attachment['preview'];
1457 $attachments[] = $attach;
1461 return $attachments;
1465 * Callback function to replace a Friendica style mention in a mention for a summary
1467 * @param array $match Matching values for the callback
1468 * @return string Replaced mention
1469 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1471 private static function mentionAddrCallback($match)
1473 if (empty($match[1])) {
1477 $data = Contact::getByURL($match[1], false, ['addr']);
1478 if (empty($data['addr'])) {
1482 return '@' . $data['addr'];
1486 * Remove image elements since they are added as attachment
1488 * @param string $body
1490 * @return string with removed images
1492 private static function removePictures($body)
1494 // Simplify image codes
1495 $body = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '[img]$3[/img]', $body);
1496 $body = preg_replace("/\[img\=(.*?)\](.*?)\[\/img\]/ism", '[img]$1[/img]', $body);
1498 // Now remove local links
1499 $body = preg_replace_callback(
1500 '/\[url=([^\[\]]*)\]\[img\](.*)\[\/img\]\[\/url\]/Usi',
1502 // We remove the link when it is a link to a local photo page
1503 if (Photo::isLocalPage($match[1])) {
1506 // otherwise we just return the link
1507 return '[url]' . $match[1] . '[/url]';
1512 // Remove all pictures
1513 $body = preg_replace("/\[img\]([^\[\]]*)\[\/img\]/Usi", '', $body);
1519 * Fetches the "context" value for a givem item array from the "conversation" table
1521 * @param array $item
1523 * @return string with context url
1524 * @throws \Exception
1526 private static function fetchContextURLForItem($item)
1528 $conversation = DBA::selectFirst('conversation', ['conversation-href', 'conversation-uri'], ['item-uri' => $item['parent-uri']]);
1529 if (DBA::isResult($conversation) && !empty($conversation['conversation-href'])) {
1530 $context_uri = $conversation['conversation-href'];
1531 } elseif (DBA::isResult($conversation) && !empty($conversation['conversation-uri'])) {
1532 $context_uri = $conversation['conversation-uri'];
1534 $context_uri = $item['parent-uri'] . '#context';
1536 return $context_uri;
1540 * Returns if the post contains sensitive content ("nsfw")
1542 * @param integer $uri_id
1545 * @throws \Exception
1547 private static function isSensitive($uri_id)
1549 return DBA::exists('tag-view', ['uri-id' => $uri_id, 'name' => 'nsfw', 'type' => Tag::HASHTAG]);
1553 * Creates event data
1555 * @param array $item
1557 * @return array with the event data
1558 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1560 private static function createEvent($item)
1563 $event['name'] = $item['event-summary'];
1564 $event['content'] = BBCode::convertForUriId($item['uri-id'], $item['event-desc'], BBCode::ACTIVITYPUB);
1565 $event['startTime'] = DateTimeFormat::utc($item['event-start'], 'c');
1567 if (!$item['event-nofinish']) {
1568 $event['endTime'] = DateTimeFormat::utc($item['event-finish'], 'c');
1571 if (!empty($item['event-location'])) {
1572 $item['location'] = $item['event-location'];
1573 $event['location'] = self::createLocation($item);
1576 // 2021.12: Backward compatibility value, all the events now "adjust" to the viewer timezone
1577 $event['dfrn:adjust'] = true;
1583 * Creates a note/article object array
1585 * @param array $item
1587 * @return array with the object data
1588 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1589 * @throws \ImagickException
1591 public static function createNote($item)
1597 // We are treating posts differently when they are directed to a community.
1598 // This is done to better support Lemmy. Most of the changes should work with other systems as well.
1599 // But to not risk compatibility issues we currently perform the changes only for communities.
1600 if ($item['gravity'] == GRAVITY_PARENT) {
1601 $isCommunityPost = !empty(Tag::getByURIId($item['uri-id'], [Tag::EXCLUSIVE_MENTION]));
1602 $links = Post\Media::getByURIId($item['uri-id'], [Post\Media::HTML]);
1603 if ($isCommunityPost && (count($links) == 1)) {
1604 $link = $links[0]['url'];
1607 $isCommunityPost = false;
1610 if ($item['event-type'] == 'event') {
1612 } elseif (!empty($item['title'])) {
1613 if (!$isCommunityPost || empty($link)) {
1616 // "Page" is used by Lemmy for posts that contain an external link
1623 if ($item['deleted']) {
1624 $type = 'Tombstone';
1628 $data['id'] = $item['uri'];
1629 $data['type'] = $type;
1631 if ($item['deleted']) {
1635 $data['summary'] = BBCode::toPlaintext(BBCode::getAbstract($item['body'], Protocol::ACTIVITYPUB));
1637 if ($item['uri'] != $item['thr-parent']) {
1638 $data['inReplyTo'] = $item['thr-parent'];
1640 $data['inReplyTo'] = null;
1643 $data['diaspora:guid'] = $item['guid'];
1644 $data['published'] = DateTimeFormat::utc($item['created'] . '+00:00', DateTimeFormat::ATOM);
1646 if ($item['created'] != $item['edited']) {
1647 $data['updated'] = DateTimeFormat::utc($item['edited'] . '+00:00', DateTimeFormat::ATOM);
1650 $data['url'] = $link ?? $item['plink'];
1651 $data['attributedTo'] = $item['author-link'];
1652 $data['sensitive'] = self::isSensitive($item['uri-id']);
1653 $data['context'] = self::fetchContextURLForItem($item);
1655 if (!empty($item['title'])) {
1656 $data['name'] = BBCode::toPlaintext($item['title'], false);
1659 $permission_block = self::createPermissionBlockForItem($item, false);
1661 $body = $item['body'];
1663 if ($type == 'Note') {
1664 $body = $item['raw-body'] ?? self::removePictures($body);
1668 * @todo Improve the automated summary
1669 * This part is currently deactivated. The automated summary seems to be more
1670 * confusing than helping. But possibly we will find a better way.
1671 * So the code is left here for now as a reminder
1673 * } elseif (($type == 'Article') && empty($data['summary'])) {
1674 * $regexp = "/[@!]\[url\=([^\[\]]*)\].*?\[\/url\]/ism";
1675 * $summary = preg_replace_callback($regexp, ['self', 'mentionAddrCallback'], $body);
1676 * $data['summary'] = BBCode::toPlaintext(Plaintext::shorten(self::removePictures($summary), 1000));
1680 if (empty($item['uid']) || !Feature::isEnabled($item['uid'], 'explicit_mentions')) {
1681 $body = self::prependMentions($body, $item['uri-id'], $item['author-link']);
1684 if ($type == 'Event') {
1685 $data = array_merge($data, self::createEvent($item));
1687 if ($isCommunityPost) {
1688 // For community posts we remove the visible "!user@domain.tld".
1689 // This improves the look at systems like Lemmy.
1690 // Also in the future we should control the community delivery via other methods.
1691 $body = preg_replace("/!\[url\=[^\[\]]*\][^\[\]]*\[\/url\]/ism", '', $body);
1694 if ($type == 'Page') {
1695 // When we transmit "Page" posts we have to remove the attachment.
1696 // The attachment contains the link that we already transmit in the "url" field.
1697 $body = preg_replace("/\s*\[attachment .*?\].*?\[\/attachment\]\s*/ism", '', $body);
1700 $body = BBCode::setMentionsToNicknames($body);
1702 $data['content'] = BBCode::convertForUriId($item['uri-id'], $body, BBCode::ACTIVITYPUB);
1705 // The regular "content" field does contain a minimized HTML. This is done since systems like
1706 // Mastodon has got problems with - for example - embedded pictures.
1707 // The contentMap does contain the unmodified HTML.
1708 $language = self::getLanguage($item);
1709 if (!empty($language)) {
1710 $richbody = BBCode::setMentionsToNicknames($item['body'] ?? '');
1711 $richbody = BBCode::removeAttachment($richbody);
1713 $data['contentMap'][$language] = BBCode::convertForUriId($item['uri-id'], $richbody, BBCode::EXTERNAL);
1716 $data['source'] = ['content' => $item['body'], 'mediaType' => "text/bbcode"];
1718 if (!empty($item['signed_text']) && ($item['uri'] != $item['thr-parent'])) {
1719 $data['diaspora:comment'] = $item['signed_text'];
1722 $data['attachment'] = self::createAttachmentList($item, $type);
1723 $data['tag'] = self::createTagList($item);
1725 if (empty($data['location']) && (!empty($item['coord']) || !empty($item['location']))) {
1726 $data['location'] = self::createLocation($item);
1729 if (!empty($item['app'])) {
1730 $data['generator'] = ['type' => 'Application', 'name' => $item['app']];
1733 $data = array_merge($data, $permission_block);
1739 * Fetches the language from the post, the user or the system.
1741 * @param array $item
1743 * @return string language string
1745 private static function getLanguage(array $item)
1747 // Try to fetch the language from the post itself
1748 if (!empty($item['language'])) {
1749 $languages = array_keys(json_decode($item['language'], true));
1750 if (!empty($languages[0])) {
1751 return $languages[0];
1755 // Otherwise use the user's language
1756 if (!empty($item['uid'])) {
1757 $user = DBA::selectFirst('user', ['language'], ['uid' => $item['uid']]);
1758 if (!empty($user['language'])) {
1759 return $user['language'];
1763 // And finally just use the system language
1764 return DI::config()->get('system', 'language');
1768 * Creates an an "add tag" entry
1770 * @param array $item
1771 * @param array $data activity data
1773 * @return array with activity data for adding tags
1774 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1775 * @throws \ImagickException
1777 private static function createAddTag($item, $data)
1779 $object = XML::parseString($item['object']);
1780 $target = XML::parseString($item["target"]);
1782 $data['diaspora:guid'] = $item['guid'];
1783 $data['actor'] = $item['author-link'];
1784 $data['target'] = (string)$target->id;
1785 $data['summary'] = BBCode::toPlaintext($item['body']);
1786 $data['object'] = ['id' => (string)$object->id, 'type' => 'tag', 'name' => (string)$object->title, 'content' => (string)$object->content];
1792 * Creates an announce object entry
1794 * @param array $item
1795 * @param array $data activity data
1797 * @return array with activity data
1798 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1799 * @throws \ImagickException
1801 private static function createAnnounce($item, $data)
1803 $orig_body = $item['body'];
1804 $announce = self::getAnnounceArray($item);
1805 if (empty($announce)) {
1806 $data['type'] = 'Create';
1807 $data['object'] = self::createNote($item);
1811 if (empty($announce['comment'])) {
1812 // Pure announce, without a quote
1813 $data['type'] = 'Announce';
1814 $data['object'] = $announce['object']['uri'];
1819 $data['type'] = 'Create';
1820 $item['body'] = $announce['comment'] . "\n" . $announce['object']['plink'];
1821 $data['object'] = self::createNote($item);
1823 /// @todo Finally descide how to implement this in AP. This is a possible way:
1824 $data['object']['attachment'][] = self::createNote($announce['object']);
1826 $data['object']['source']['content'] = $orig_body;
1831 * Return announce related data if the item is an annunce
1833 * @param array $item
1837 public static function getAnnounceArray($item)
1839 $reshared = Item::getShareArray($item);
1840 if (empty($reshared['guid'])) {
1844 $reshared_item = Post::selectFirst(Item::DELIVER_FIELDLIST, ['guid' => $reshared['guid']]);
1845 if (!DBA::isResult($reshared_item)) {
1849 if (!in_array($reshared_item['network'], [Protocol::ACTIVITYPUB, Protocol::DFRN])) {
1853 $profile = APContact::getByURL($reshared_item['author-link'], false);
1854 if (empty($profile)) {
1858 return ['object' => $reshared_item, 'actor' => $profile, 'comment' => $reshared['comment']];
1862 * Checks if the provided item array is an announce
1864 * @param array $item
1868 public static function isAnnounce($item)
1870 if (!empty($item['verb']) && ($item['verb'] == Activity::ANNOUNCE)) {
1874 $announce = self::getAnnounceArray($item);
1875 if (empty($announce)) {
1879 return empty($announce['comment']);
1883 * Creates an activity id for a given contact id
1885 * @param integer $cid Contact ID of target
1887 * @return bool|string activity id
1889 public static function activityIDFromContact($cid)
1891 $contact = DBA::selectFirst('contact', ['uid', 'id', 'created'], ['id' => $cid]);
1892 if (!DBA::isResult($contact)) {
1896 $hash = hash('ripemd128', $contact['uid'].'-'.$contact['id'].'-'.$contact['created']);
1897 $uuid = substr($hash, 0, 8). '-' . substr($hash, 8, 4) . '-' . substr($hash, 12, 4) . '-' . substr($hash, 16, 4) . '-' . substr($hash, 20, 12);
1898 return DI::baseUrl() . '/activity/' . $uuid;
1902 * Transmits a contact suggestion to a given inbox
1904 * @param integer $uid User ID
1905 * @param string $inbox Target inbox
1906 * @param integer $suggestion_id Suggestion ID
1908 * @return boolean was the transmission successful?
1909 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1911 public static function sendContactSuggestion($uid, $inbox, $suggestion_id)
1913 $owner = User::getOwnerDataById($uid);
1915 $suggestion = DI::fsuggest()->selectOneById($suggestion_id);
1917 $data = ['@context' => ActivityPub::CONTEXT,
1918 'id' => DI::baseUrl() . '/activity/' . System::createGUID(),
1919 'type' => 'Announce',
1920 'actor' => $owner['url'],
1921 'object' => $suggestion->url,
1922 'content' => $suggestion->note,
1923 'instrument' => self::getService(),
1924 'to' => [ActivityPub::PUBLIC_COLLECTION],
1927 $signed = LDSignature::sign($data, $owner);
1929 Logger::info('Deliver profile deletion for user ' . $uid . ' to ' . $inbox . ' via ActivityPub');
1930 return HTTPSignature::transmit($signed, $inbox, $uid);
1934 * Transmits a profile relocation to a given inbox
1936 * @param integer $uid User ID
1937 * @param string $inbox Target inbox
1939 * @return boolean was the transmission successful?
1940 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1942 public static function sendProfileRelocation($uid, $inbox)
1944 $owner = User::getOwnerDataById($uid);
1946 $data = ['@context' => ActivityPub::CONTEXT,
1947 'id' => DI::baseUrl() . '/activity/' . System::createGUID(),
1948 'type' => 'dfrn:relocate',
1949 'actor' => $owner['url'],
1950 'object' => $owner['url'],
1951 'published' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
1952 'instrument' => self::getService(),
1953 'to' => [ActivityPub::PUBLIC_COLLECTION],
1956 $signed = LDSignature::sign($data, $owner);
1958 Logger::info('Deliver profile relocation for user ' . $uid . ' to ' . $inbox . ' via ActivityPub');
1959 return HTTPSignature::transmit($signed, $inbox, $uid);
1963 * Transmits a profile deletion to a given inbox
1965 * @param integer $uid User ID
1966 * @param string $inbox Target inbox
1968 * @return boolean was the transmission successful?
1969 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1971 public static function sendProfileDeletion($uid, $inbox)
1973 $owner = User::getOwnerDataById($uid);
1975 if (empty($owner)) {
1976 Logger::error('No owner data found, the deletion message cannot be processed.', ['user' => $uid]);
1980 if (empty($owner['uprvkey'])) {
1981 Logger::error('No private key for owner found, the deletion message cannot be processed.', ['user' => $uid]);
1985 $data = ['@context' => ActivityPub::CONTEXT,
1986 'id' => DI::baseUrl() . '/activity/' . System::createGUID(),
1988 'actor' => $owner['url'],
1989 'object' => $owner['url'],
1990 'published' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
1991 'instrument' => self::getService(),
1992 'to' => [ActivityPub::PUBLIC_COLLECTION],
1995 $signed = LDSignature::sign($data, $owner);
1997 Logger::info('Deliver profile deletion for user ' . $uid . ' to ' . $inbox . ' via ActivityPub');
1998 return HTTPSignature::transmit($signed, $inbox, $uid);
2002 * Transmits a profile change to a given inbox
2004 * @param integer $uid User ID
2005 * @param string $inbox Target inbox
2007 * @return boolean was the transmission successful?
2008 * @throws HTTPException\InternalServerErrorException
2009 * @throws HTTPException\NotFoundException
2010 * @throws \ImagickException
2012 public static function sendProfileUpdate(int $uid, string $inbox): bool
2014 $owner = User::getOwnerDataById($uid);
2015 $profile = APContact::getByURL($owner['url']);
2017 $data = ['@context' => ActivityPub::CONTEXT,
2018 'id' => DI::baseUrl() . '/activity/' . System::createGUID(),
2020 'actor' => $owner['url'],
2021 'object' => self::getProfile($uid),
2022 'published' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
2023 'instrument' => self::getService(),
2024 'to' => [$profile['followers']],
2027 $signed = LDSignature::sign($data, $owner);
2029 Logger::info('Deliver profile update for user ' . $uid . ' to ' . $inbox . ' via ActivityPub');
2030 return HTTPSignature::transmit($signed, $inbox, $uid);
2034 * Transmits a given activity to a target
2036 * @param string $activity Type name
2037 * @param string $target Target profile
2038 * @param integer $uid User ID
2040 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2041 * @throws \ImagickException
2042 * @throws \Exception
2044 public static function sendActivity($activity, $target, $uid, $id = '')
2046 $profile = APContact::getByURL($target);
2047 if (empty($profile['inbox'])) {
2048 Logger::warning('No inbox found for target', ['target' => $target, 'profile' => $profile]);
2052 $owner = User::getOwnerDataById($uid);
2055 $id = DI::baseUrl() . '/activity/' . System::createGUID();
2058 $data = ['@context' => ActivityPub::CONTEXT,
2060 'type' => $activity,
2061 'actor' => $owner['url'],
2062 'object' => $profile['url'],
2063 'instrument' => self::getService(),
2064 'to' => [$profile['url']]];
2066 Logger::info('Sending activity ' . $activity . ' to ' . $target . ' for user ' . $uid);
2068 $signed = LDSignature::sign($data, $owner);
2069 return HTTPSignature::transmit($signed, $profile['inbox'], $uid);
2073 * Transmits a "follow object" activity to a target
2074 * This is a preparation for sending automated "follow" requests when receiving "Announce" messages
2076 * @param string $object Object URL
2077 * @param string $target Target profile
2078 * @param integer $uid User ID
2080 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2081 * @throws \ImagickException
2082 * @throws \Exception
2084 public static function sendFollowObject($object, $target, $uid = 0)
2086 $profile = APContact::getByURL($target);
2087 if (empty($profile['inbox'])) {
2088 Logger::warning('No inbox found for target', ['target' => $target, 'profile' => $profile]);
2093 // Fetch the list of administrators
2094 $admin_mail = explode(',', str_replace(' ', '', DI::config()->get('config', 'admin_email')));
2096 // We need to use some user as a sender. It doesn't care who it will send. We will use an administrator account.
2097 $condition = ['verified' => true, 'blocked' => false, 'account_removed' => false, 'account_expired' => false, 'email' => $admin_mail];
2098 $first_user = DBA::selectFirst('user', ['uid'], $condition);
2099 $uid = $first_user['uid'];
2102 $condition = ['verb' => Activity::FOLLOW, 'uid' => 0, 'parent-uri' => $object,
2103 'author-id' => Contact::getPublicIdByUserId($uid)];
2104 if (Post::exists($condition)) {
2105 Logger::info('Follow for ' . $object . ' for user ' . $uid . ' does already exist.');
2109 $owner = User::getOwnerDataById($uid);
2111 $data = ['@context' => ActivityPub::CONTEXT,
2112 'id' => DI::baseUrl() . '/activity/' . System::createGUID(),
2114 'actor' => $owner['url'],
2115 'object' => $object,
2116 'instrument' => self::getService(),
2117 'to' => [$profile['url']]];
2119 Logger::info('Sending follow ' . $object . ' to ' . $target . ' for user ' . $uid);
2121 $signed = LDSignature::sign($data, $owner);
2122 return HTTPSignature::transmit($signed, $profile['inbox'], $uid);
2126 * Transmit a message that the contact request had been accepted
2128 * @param string $target Target profile
2130 * @param integer $uid User ID
2131 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2132 * @throws \ImagickException
2134 public static function sendContactAccept($target, $id, $uid)
2136 $profile = APContact::getByURL($target);
2137 if (empty($profile['inbox'])) {
2138 Logger::warning('No inbox found for target', ['target' => $target, 'profile' => $profile]);
2142 $owner = User::getOwnerDataById($uid);
2143 $data = ['@context' => ActivityPub::CONTEXT,
2144 'id' => DI::baseUrl() . '/activity/' . System::createGUID(),
2146 'actor' => $owner['url'],
2148 'id' => (string)$id,
2150 'actor' => $profile['url'],
2151 'object' => $owner['url']
2153 'instrument' => self::getService(),
2154 'to' => [$profile['url']]];
2156 Logger::debug('Sending accept to ' . $target . ' for user ' . $uid . ' with id ' . $id);
2158 $signed = LDSignature::sign($data, $owner);
2159 HTTPSignature::transmit($signed, $profile['inbox'], $uid);
2163 * Reject a contact request or terminates the contact relation
2165 * @param string $target Target profile
2167 * @param integer $uid User ID
2168 * @return bool Operation success
2169 * @throws HTTPException\InternalServerErrorException
2170 * @throws \ImagickException
2172 public static function sendContactReject($target, $id, $uid): bool
2174 $profile = APContact::getByURL($target);
2175 if (empty($profile['inbox'])) {
2176 Logger::warning('No inbox found for target', ['target' => $target, 'profile' => $profile]);
2180 $owner = User::getOwnerDataById($uid);
2181 $data = ['@context' => ActivityPub::CONTEXT,
2182 'id' => DI::baseUrl() . '/activity/' . System::createGUID(),
2184 'actor' => $owner['url'],
2186 'id' => (string)$id,
2188 'actor' => $profile['url'],
2189 'object' => $owner['url']
2191 'instrument' => self::getService(),
2192 'to' => [$profile['url']]];
2194 Logger::debug('Sending reject to ' . $target . ' for user ' . $uid . ' with id ' . $id);
2196 $signed = LDSignature::sign($data, $owner);
2197 return HTTPSignature::transmit($signed, $profile['inbox'], $uid);
2201 * Transmits a message that we don't want to follow this contact anymore
2203 * @param string $target Target profile
2204 * @param integer $uid User ID
2205 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2206 * @throws \ImagickException
2207 * @throws \Exception
2208 * @return bool success
2210 public static function sendContactUndo($target, $cid, $uid)
2212 $profile = APContact::getByURL($target);
2213 if (empty($profile['inbox'])) {
2214 Logger::warning('No inbox found for target', ['target' => $target, 'profile' => $profile]);
2218 $object_id = self::activityIDFromContact($cid);
2219 if (empty($object_id)) {
2223 $id = DI::baseUrl() . '/activity/' . System::createGUID();
2225 $owner = User::getOwnerDataById($uid);
2226 $data = ['@context' => ActivityPub::CONTEXT,
2229 'actor' => $owner['url'],
2230 'object' => ['id' => $object_id, 'type' => 'Follow',
2231 'actor' => $owner['url'],
2232 'object' => $profile['url']],
2233 'instrument' => self::getService(),
2234 'to' => [$profile['url']]];
2236 Logger::info('Sending undo to ' . $target . ' for user ' . $uid . ' with id ' . $id);
2238 $signed = LDSignature::sign($data, $owner);
2239 return HTTPSignature::transmit($signed, $profile['inbox'], $uid);
2242 private static function prependMentions($body, int $uriid, string $authorLink)
2246 foreach (Tag::getByURIId($uriid, [Tag::IMPLICIT_MENTION]) as $tag) {
2247 $profile = Contact::getByURL($tag['url'], false, ['addr', 'contact-type', 'nick']);
2248 if (!empty($profile['addr'])
2249 && $profile['contact-type'] != Contact::TYPE_COMMUNITY
2250 && !strstr($body, $profile['addr'])
2251 && !strstr($body, $tag['url'])
2252 && $tag['url'] !== $authorLink
2254 $mentions[] = '@[url=' . $tag['url'] . ']' . $profile['nick'] . '[/url]';
2258 $mentions[] = $body;
2260 return implode(' ', $mentions);