3 * @copyright Copyright (C) 2010-2022, the Friendica project
5 * @license GNU AGPL version 3 or any later version
7 * This program is free software: you can redistribute it and/or modify
8 * it under the terms of the GNU Affero General Public License as
9 * published by the Free Software Foundation, either version 3 of the
10 * License, or (at your option) any later version.
12 * This program is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU Affero General Public License for more details.
17 * You should have received a copy of the GNU Affero General Public License
18 * along with this program. If not, see <https://www.gnu.org/licenses/>.
22 namespace Friendica\Protocol\ActivityPub;
24 use Friendica\Content\Feature;
25 use Friendica\Content\Text\BBCode;
26 use Friendica\Core\Cache\Enum\Duration;
27 use Friendica\Core\Logger;
28 use Friendica\Core\Protocol;
29 use Friendica\Core\System;
30 use Friendica\Database\DBA;
32 use Friendica\Model\APContact;
33 use Friendica\Model\Contact;
34 use Friendica\Model\Conversation;
35 use Friendica\Model\GServer;
36 use Friendica\Model\Item;
37 use Friendica\Model\Photo;
38 use Friendica\Model\Post;
39 use Friendica\Model\Tag;
40 use Friendica\Model\User;
41 use Friendica\Network\HTTPException;
42 use Friendica\Protocol\Activity;
43 use Friendica\Protocol\ActivityPub;
44 use Friendica\Protocol\Relay;
45 use Friendica\Util\DateTimeFormat;
46 use Friendica\Util\HTTPSignature;
47 use Friendica\Util\JsonLD;
48 use Friendica\Util\LDSignature;
49 use Friendica\Util\Map;
50 use Friendica\Util\Network;
51 use Friendica\Util\Strings;
52 use Friendica\Util\XML;
55 * ActivityPub Transmitter Protocol class
63 * Add relay servers to the list of inboxes
65 * @param array $inboxes
66 * @return array inboxes with added relay servers
68 public static function addRelayServerInboxes(array $inboxes = [])
70 foreach (Relay::getList(['inbox']) as $contact) {
71 $inboxes[$contact['inbox']] = $contact['inbox'];
78 * Add relay servers to the list of inboxes
80 * @param array $inboxes
81 * @return array inboxes with added relay servers
83 public static function addRelayServerInboxesForItem(int $item_id, array $inboxes = [])
85 $item = Post::selectFirst(['uid'], ['id' => $item_id]);
90 $relays = Relay::getDirectRelayList($item_id);
95 foreach ($relays as $relay) {
96 $contact = Contact::getByURLForUser($relay['url'], $item['uid'], false, ['id']);
97 $inboxes[$relay['batch']][] = $contact['id'] ?? 0;
103 * Subscribe to a relay
105 * @param string $url Subscribe actor url
106 * @return bool success
108 public static function sendRelayFollow(string $url)
110 $contact = Contact::getByURL($url);
111 if (empty($contact)) {
115 $activity_id = ActivityPub\Transmitter::activityIDFromContact($contact['id']);
116 $success = ActivityPub\Transmitter::sendActivity('Follow', $url, 0, $activity_id);
118 Contact::update(['rel' => Contact::FRIEND], ['id' => $contact['id']]);
125 * Unsubscribe from a relay
127 * @param string $url Subscribe actor url
128 * @param bool $force Set the relay status as non follower even if unsubscribe hadn't worked
129 * @return bool success
131 public static function sendRelayUndoFollow(string $url, bool $force = false)
133 $contact = Contact::getByURL($url);
134 if (empty($contact)) {
138 $success = self::sendContactUndo($url, $contact['id'], 0);
139 if ($success || $force) {
140 Contact::update(['rel' => Contact::NOTHING], ['id' => $contact['id']]);
147 * Collects a list of contacts of the given owner
149 * @param array $owner Owner array
150 * @param int|array $rel The relevant value(s) contact.rel should match
151 * @param string $module The name of the relevant AP endpoint module (followers|following)
152 * @param integer $page Page number
153 * @param string $requester URL of the requester
155 * @return array of owners
158 public static function getContacts($owner, $rel, $module, $page = null, string $requester = null)
162 'uid' => $owner['uid'],
171 $condition = DBA::mergeConditions($parameters, ["`url` IN (SELECT `url` FROM `apcontact`)"]);
173 $total = DBA::count('contact', $condition);
175 $modulePath = '/' . $module . '/';
177 $data = ['@context' => ActivityPub::CONTEXT];
178 $data['id'] = DI::baseUrl() . $modulePath . $owner['nickname'];
179 $data['type'] = 'OrderedCollection';
180 $data['totalItems'] = $total;
182 // When we hide our friends we will only show the pure number but don't allow more.
183 $show_contacts = empty($owner['hide-friends']);
185 // Allow fetching the contact list when the requester is part of the list.
186 if (($owner['page-flags'] == User::PAGE_FLAGS_PRVGROUP) && !empty($requester)) {
187 $show_contacts = DBA::exists('contact', ['nurl' => Strings::normaliseLink($requester), 'uid' => $owner['uid'], 'blocked' => false]);
190 if (!$show_contacts) {
195 $data['first'] = DI::baseUrl() . $modulePath . $owner['nickname'] . '?page=1';
197 $data['type'] = 'OrderedCollectionPage';
200 $contacts = DBA::select('contact', ['url'], $condition, ['limit' => [($page - 1) * 100, 100]]);
201 while ($contact = DBA::fetch($contacts)) {
202 $list[] = $contact['url'];
204 DBA::close($contacts);
207 $data['next'] = DI::baseUrl() . $modulePath . $owner['nickname'] . '?page=' . ($page + 1);
210 $data['partOf'] = DI::baseUrl() . $modulePath . $owner['nickname'];
212 $data['orderedItems'] = $list;
219 * Public posts for the given owner
221 * @param array $owner Owner array
222 * @param integer $page Page number
223 * @param string $requester URL of requesting account
225 * @return array of posts
226 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
227 * @throws \ImagickException
229 public static function getOutbox($owner, $page = null, $requester = '')
231 $condition = ['private' => [Item::PUBLIC, Item::UNLISTED]];
233 if (!empty($requester)) {
234 $requester_id = Contact::getIdForURL($requester, $owner['uid']);
235 if (!empty($requester_id)) {
236 $permissionSets = DI::permissionSet()->selectByContactId($requester_id, $owner['uid']);
237 if (!empty($permissionSets)) {
238 $condition = ['psid' => array_merge($permissionSets->column('id'),
239 [DI::permissionSet()->selectPublicForUser($owner['uid'])])];
244 $condition = array_merge($condition,
245 ['uid' => $owner['uid'],
246 'author-id' => Contact::getIdForURL($owner['url'], 0, false),
247 'gravity' => [GRAVITY_PARENT, GRAVITY_COMMENT],
248 'network' => Protocol::FEDERATED,
249 'parent-network' => Protocol::FEDERATED,
254 $count = Post::count($condition);
256 $data = ['@context' => ActivityPub::CONTEXT];
257 $data['id'] = DI::baseUrl() . '/outbox/' . $owner['nickname'];
258 $data['type'] = 'OrderedCollection';
259 $data['totalItems'] = $count;
262 $data['first'] = DI::baseUrl() . '/outbox/' . $owner['nickname'] . '?page=1';
264 $data['type'] = 'OrderedCollectionPage';
267 $items = Post::select(['id'], $condition, ['limit' => [($page - 1) * 20, 20], 'order' => ['created' => true]]);
268 while ($item = Post::fetch($items)) {
269 $activity = self::createActivityFromItem($item['id'], true);
270 $activity['type'] = $activity['type'] == 'Update' ? 'Create' : $activity['type'];
272 // Only list "Create" activity objects here, no reshares
273 if (!empty($activity['object']) && ($activity['type'] == 'Create')) {
274 $list[] = $activity['object'];
280 $data['next'] = DI::baseUrl() . '/outbox/' . $owner['nickname'] . '?page=' . ($page + 1);
283 $data['partOf'] = DI::baseUrl() . '/outbox/' . $owner['nickname'];
285 $data['orderedItems'] = $list;
292 * Return the service array containing information the used software and it's url
294 * @return array with service data
296 private static function getService()
298 return ['type' => 'Service',
299 'name' => FRIENDICA_PLATFORM . " '" . FRIENDICA_CODENAME . "' " . FRIENDICA_VERSION . '-' . DB_UPDATE_VERSION,
300 'url' => DI::baseUrl()->get()];
304 * Return the ActivityPub profile of the given user
306 * @param int $uid User ID
307 * @return array with profile data
308 * @throws HTTPException\NotFoundException
309 * @throws HTTPException\InternalServerErrorException
311 public static function getProfile(int $uid): array
313 $owner = User::getOwnerDataById($uid);
314 if (!isset($owner['id'])) {
315 DI::logger()->error('Unable to find owner data for uid', ['uid' => $uid, 'callstack' => System::callstack(20)]);
316 throw new HTTPException\NotFoundException('User not found.');
319 $data = ['@context' => ActivityPub::CONTEXT];
320 $data['id'] = $owner['url'];
322 if (!empty($owner['guid'])) {
323 $data['diaspora:guid'] = $owner['guid'];
326 $data['type'] = ActivityPub::ACCOUNT_TYPES[$owner['account-type']];
329 $data['following'] = DI::baseUrl() . '/following/' . $owner['nick'];
330 $data['followers'] = DI::baseUrl() . '/followers/' . $owner['nick'];
331 $data['inbox'] = DI::baseUrl() . '/inbox/' . $owner['nick'];
332 $data['outbox'] = DI::baseUrl() . '/outbox/' . $owner['nick'];
334 $data['inbox'] = DI::baseUrl() . '/friendica/inbox';
337 $data['preferredUsername'] = $owner['nick'];
338 $data['name'] = $owner['name'];
340 if (!empty($owner['country-name'] . $owner['region'] . $owner['locality'])) {
341 $data['vcard:hasAddress'] = ['@type' => 'vcard:Home', 'vcard:country-name' => $owner['country-name'],
342 'vcard:region' => $owner['region'], 'vcard:locality' => $owner['locality']];
345 if (!empty($owner['about'])) {
346 $data['summary'] = BBCode::convertForUriId($owner['uri-id'] ?? 0, $owner['about'], BBCode::EXTERNAL);
349 if (!empty($owner['xmpp']) || !empty($owner['matrix'])) {
350 $data['vcard:hasInstantMessage'] = [];
352 if (!empty($owner['xmpp'])) {
353 $data['vcard:hasInstantMessage'][] = 'xmpp:' . $owner['xmpp'];
355 if (!empty($owner['matrix'])) {
356 $data['vcard:hasInstantMessage'][] = 'matrix:' . $owner['matrix'];
360 $data['url'] = $owner['url'];
361 $data['manuallyApprovesFollowers'] = in_array($owner['page-flags'], [User::PAGE_FLAGS_NORMAL, User::PAGE_FLAGS_PRVGROUP]);
362 $data['discoverable'] = (bool)$owner['net-publish'];
363 $data['publicKey'] = ['id' => $owner['url'] . '#main-key',
364 'owner' => $owner['url'],
365 'publicKeyPem' => $owner['pubkey']];
366 $data['endpoints'] = ['sharedInbox' => DI::baseUrl() . '/inbox'];
367 $data['icon'] = ['type' => 'Image', 'url' => User::getAvatarUrl($owner)];
369 $resourceid = Photo::ridFromURI($owner['photo']);
370 if (!empty($resourceid)) {
371 $photo = Photo::selectFirst(['type'], ["resource-id" => $resourceid]);
372 if (!empty($photo['type'])) {
373 $data['icon']['mediaType'] = $photo['type'];
377 if (!empty($owner['header'])) {
378 $data['image'] = ['type' => 'Image', 'url' => Contact::getHeaderUrlForId($owner['id'], '', $owner['updated'])];
380 $resourceid = Photo::ridFromURI($owner['header']);
381 if (!empty($resourceid)) {
382 $photo = Photo::selectFirst(['type'], ["resource-id" => $resourceid]);
383 if (!empty($photo['type'])) {
384 $data['image']['mediaType'] = $photo['type'];
391 foreach (DI::profileField()->selectByContactId(0, $uid) as $profile_field) {
393 'type' => 'PropertyValue',
394 'name' => $profile_field->label,
395 'value' => BBCode::convertForUriId($owner['uri-id'], $profile_field->value)
399 if (!empty($custom_fields)) {
400 $data['attachment'] = $custom_fields;
403 $data['generator'] = self::getService();
405 // tags: https://kitty.town/@inmysocks/100656097926961126.json
410 * @param string $username
412 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
414 public static function getDeletedUser($username)
417 '@context' => ActivityPub::CONTEXT,
418 'id' => DI::baseUrl() . '/profile/' . $username,
419 'type' => 'Tombstone',
420 'published' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
421 'updated' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
422 'deleted' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
427 * Returns an array with permissions of the thread parent of the given item array
431 * @return array with permissions
432 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
433 * @throws \ImagickException
435 public static function fetchPermissionBlockFromThreadParent($item)
437 if (empty($item['thr-parent-id'])) {
441 $parent = Post::selectFirstPost(['author-link'], ['uri-id' => $item['thr-parent-id']]);
442 if (empty($parent)) {
447 'to' => [$parent['author-link']],
453 $parent_profile = APContact::getByURL($parent['author-link']);
455 $item_profile = APContact::getByURL($item['author-link']);
456 $exclude[] = $item['author-link'];
458 if ($item['gravity'] == GRAVITY_PARENT) {
459 $exclude[] = $item['owner-link'];
462 $type = [Tag::TO => 'to', Tag::CC => 'cc', Tag::BTO => 'bto', Tag::BCC => 'bcc'];
463 foreach (Tag::getByURIId($item['thr-parent-id'], [Tag::TO, Tag::CC, Tag::BTO, Tag::BCC]) as $receiver) {
464 if (!empty($parent_profile['followers']) && $receiver['url'] == $parent_profile['followers'] && !empty($item_profile['followers'])) {
465 $permissions[$type[$receiver['type']]][] = $item_profile['followers'];
466 } elseif (!in_array($receiver['url'], $exclude)) {
467 $permissions[$type[$receiver['type']]][] = $receiver['url'];
475 * Check if the given item id is from ActivityPub
477 * @param integer $item_id
478 * @return boolean "true" if the post is from ActivityPub
480 private static function isAPPost(int $item_id)
482 if (empty($item_id)) {
486 return Post::exists(['id' => $item_id, 'network' => Protocol::ACTIVITYPUB]);
490 * Creates an array of permissions from an item thread
492 * @param array $item Item array
493 * @param boolean $blindcopy addressing via "bcc" or "cc"?
494 * @param integer $last_id Last item id for adding receivers
496 * @return array with permission data
497 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
498 * @throws \ImagickException
500 private static function createPermissionBlockForItem($item, $blindcopy, $last_id = 0)
503 $last_id = $item['id'];
510 // Check if we should always deliver our stuff via BCC
511 if (!empty($item['uid'])) {
512 $owner = User::getOwnerDataById($item['uid']);
513 if (!empty($owner)) {
514 $always_bcc = $owner['hide-friends'];
515 $is_forum = ($owner['account-type'] == User::ACCOUNT_TYPE_COMMUNITY) && $owner['manually-approve'];
517 $profile = APContact::getByURL($owner['url'], false);
518 $follower = $profile['followers'] ?? '';
522 if (DI::config()->get('system', 'ap_always_bcc')) {
526 if (self::isAnnounce($item) || DI::config()->get('debug', 'total_ap_delivery') || self::isAPPost($last_id)) {
527 // Will be activated in a later step
528 $networks = Protocol::FEDERATED;
530 // For now only send to these contacts:
531 $networks = [Protocol::ACTIVITYPUB, Protocol::OSTATUS];
534 $data = ['to' => [], 'cc' => [], 'bcc' => []];
536 if ($item['gravity'] == GRAVITY_PARENT) {
537 $actor_profile = APContact::getByURL($item['owner-link']);
539 $actor_profile = APContact::getByURL($item['author-link']);
544 $terms = Tag::getByURIId($item['uri-id'], [Tag::MENTION, Tag::IMPLICIT_MENTION, Tag::EXCLUSIVE_MENTION]);
546 if ($item['private'] != Item::PRIVATE) {
547 // Directly mention the original author upon a quoted reshare.
548 // Else just ensure that the original author receives the reshare.
549 $announce = self::getAnnounceArray($item);
550 if (!empty($announce['comment'])) {
551 $data['to'][] = $announce['actor']['url'];
552 } elseif (!empty($announce)) {
553 $data['cc'][] = $announce['actor']['url'];
556 $data = array_merge($data, self::fetchPermissionBlockFromThreadParent($item));
558 // Check if the item is completely public or unlisted
559 if ($item['private'] == Item::PUBLIC) {
560 $data['to'][] = ActivityPub::PUBLIC_COLLECTION;
562 $data['cc'][] = ActivityPub::PUBLIC_COLLECTION;
565 foreach ($terms as $term) {
566 $profile = APContact::getByURL($term['url'], false);
567 if (!empty($profile)) {
568 if ($term['type'] == Tag::EXCLUSIVE_MENTION) {
570 if (!empty($profile['followers']) && ($profile['type'] == 'Group')) {
571 $data['cc'][] = $profile['followers'];
574 $data['to'][] = $profile['url'];
578 $receiver_list = Item::enumeratePermissions($item, true);
580 foreach ($terms as $term) {
581 $cid = Contact::getIdForURL($term['url'], $item['uid']);
582 if (!empty($cid) && in_array($cid, $receiver_list)) {
583 $contact = DBA::selectFirst('contact', ['url', 'network', 'protocol', 'gsid'], ['id' => $cid, 'network' => Protocol::FEDERATED]);
584 if (!DBA::isResult($contact) || !self::isAPContact($contact, $networks)) {
588 $profile = APContact::getByURL($term['url'], false);
589 if (!empty($profile)) {
590 if ($term['type'] == Tag::EXCLUSIVE_MENTION) {
592 if (!empty($profile['followers']) && ($profile['type'] == 'Group')) {
593 $data['cc'][] = $profile['followers'];
596 $data['to'][] = $profile['url'];
601 if ($is_forum && !$exclusive && !empty($follower)) {
602 $data['cc'][] = $follower;
603 } elseif (!$exclusive) {
604 foreach ($receiver_list as $receiver) {
605 $contact = DBA::selectFirst('contact', ['url', 'hidden', 'network', 'protocol', 'gsid'], ['id' => $receiver, 'network' => Protocol::FEDERATED]);
606 if (!DBA::isResult($contact) || !self::isAPContact($contact, $networks)) {
610 if (!empty($profile = APContact::getByURL($contact['url'], false))) {
611 if ($contact['hidden'] || $always_bcc) {
612 $data['bcc'][] = $profile['url'];
614 $data['cc'][] = $profile['url'];
621 if (!empty($item['parent'])) {
622 $parents = Post::select(['id', 'author-link', 'owner-link', 'gravity', 'uri'], ['parent' => $item['parent']]);
623 while ($parent = Post::fetch($parents)) {
624 if ($parent['gravity'] == GRAVITY_PARENT) {
625 $profile = APContact::getByURL($parent['owner-link'], false);
626 if (!empty($profile)) {
627 if ($item['gravity'] != GRAVITY_PARENT) {
628 // Comments to forums are directed to the forum
629 // But comments to forums aren't directed to the followers collection
630 // This rule is only valid when the actor isn't the forum.
631 // The forum needs to transmit their content to their followers.
632 if (($profile['type'] == 'Group') && ($profile['url'] != ($actor_profile['url'] ?? ''))) {
633 $data['to'][] = $profile['url'];
635 $data['cc'][] = $profile['url'];
636 if (($item['private'] != Item::PRIVATE) && !empty($actor_profile['followers'])) {
637 $data['cc'][] = $actor_profile['followers'];
640 } elseif (!$exclusive) {
641 // Public thread parent post always are directed to the followers.
642 if ($item['private'] != Item::PRIVATE) {
643 $data['cc'][] = $actor_profile['followers'];
649 // Don't include data from future posts
650 if ($parent['id'] >= $last_id) {
654 $profile = APContact::getByURL($parent['author-link'], false);
655 if (!empty($profile)) {
656 if (($profile['type'] == 'Group') || ($parent['uri'] == $item['thr-parent'])) {
657 $data['to'][] = $profile['url'];
659 $data['cc'][] = $profile['url'];
663 DBA::close($parents);
666 $data['to'] = array_unique($data['to']);
667 $data['cc'] = array_unique($data['cc']);
668 $data['bcc'] = array_unique($data['bcc']);
670 if (($key = array_search($item['author-link'], $data['to'])) !== false) {
671 unset($data['to'][$key]);
674 if (($key = array_search($item['author-link'], $data['cc'])) !== false) {
675 unset($data['cc'][$key]);
678 if (($key = array_search($item['author-link'], $data['bcc'])) !== false) {
679 unset($data['bcc'][$key]);
682 foreach ($data['to'] as $to) {
683 if (($key = array_search($to, $data['cc'])) !== false) {
684 unset($data['cc'][$key]);
687 if (($key = array_search($to, $data['bcc'])) !== false) {
688 unset($data['bcc'][$key]);
692 foreach ($data['cc'] as $cc) {
693 if (($key = array_search($cc, $data['bcc'])) !== false) {
694 unset($data['bcc'][$key]);
698 $receivers = ['to' => array_values($data['to']), 'cc' => array_values($data['cc']), 'bcc' => array_values($data['bcc'])];
701 unset($receivers['bcc']);
704 foreach (['to' => Tag::TO, 'cc' => Tag::CC, 'bcc' => Tag::BCC] as $element => $type) {
705 if (!empty($receivers[$element])) {
706 foreach ($receivers[$element] as $receiver) {
707 if ($receiver == ActivityPub::PUBLIC_COLLECTION) {
708 $name = Receiver::PUBLIC_COLLECTION;
710 $name = trim(parse_url($receiver, PHP_URL_PATH), '/');
712 Tag::store($item['uri-id'], $type, $name, $receiver);
721 * Check if an inbox is archived
723 * @param string $url Inbox url
725 * @return boolean "true" if inbox is archived
727 public static function archivedInbox($url)
729 return DBA::exists('inbox-status', ['url' => $url, 'archive' => true]);
733 * Check if a given contact should be delivered via AP
735 * @param array $contact
736 * @param array $networks
740 private static function isAPContact(array $contact, array $networks)
742 if (in_array($contact['network'], $networks) || ($contact['protocol'] == Protocol::ACTIVITYPUB)) {
746 return GServer::getProtocol($contact['gsid'] ?? 0) == Post\DeliveryData::ACTIVITYPUB;
750 * Fetches a list of inboxes of followers of a given user
752 * @param integer $uid User ID
753 * @param boolean $personal fetch personal inboxes
754 * @param boolean $all_ap Retrieve all AP enabled inboxes
756 * @return array of follower inboxes
757 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
758 * @throws \ImagickException
760 public static function fetchTargetInboxesforUser($uid, $personal = false, bool $all_ap = false)
766 if (!empty($item['uid'])) {
767 $profile = User::getOwnerDataById($item['uid']);
768 if (!empty($profile)) {
769 $isforum = $profile['account-type'] == User::ACCOUNT_TYPE_COMMUNITY;
773 if (DI::config()->get('debug', 'total_ap_delivery') || $all_ap) {
774 // Will be activated in a later step
775 $networks = Protocol::FEDERATED;
777 // For now only send to these contacts:
778 $networks = [Protocol::ACTIVITYPUB, Protocol::OSTATUS];
781 $condition = ['uid' => $uid, 'archive' => false, 'pending' => false, 'blocked' => false, 'network' => Protocol::FEDERATED];
784 $condition['rel'] = [Contact::FOLLOWER, Contact::FRIEND];
787 $contacts = DBA::select('contact', ['id', 'url', 'network', 'protocol', 'gsid'], $condition);
788 while ($contact = DBA::fetch($contacts)) {
789 if (!self::isAPContact($contact, $networks)) {
793 if ($isforum && ($contact['network'] == Protocol::DFRN)) {
797 if (Network::isUrlBlocked($contact['url'])) {
801 $profile = APContact::getByURL($contact['url'], false);
802 if (!empty($profile)) {
803 if (empty($profile['sharedinbox']) || $personal || Contact::isLocal($contact['url'])) {
804 $target = $profile['inbox'];
806 $target = $profile['sharedinbox'];
808 if (!self::archivedInbox($target)) {
809 $inboxes[$target][] = $contact['id'];
813 DBA::close($contacts);
819 * Fetches an array of inboxes for the given item and user
821 * @param array $item Item array
822 * @param integer $uid User ID
823 * @param boolean $personal fetch personal inboxes
824 * @param integer $last_id Last item id for adding receivers
825 * @return array with inboxes
826 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
827 * @throws \ImagickException
829 public static function fetchTargetInboxes($item, $uid, $personal = false, $last_id = 0)
831 $permissions = self::createPermissionBlockForItem($item, true, $last_id);
832 if (empty($permissions)) {
838 if ($item['gravity'] == GRAVITY_ACTIVITY) {
839 $item_profile = APContact::getByURL($item['author-link'], false);
841 $item_profile = APContact::getByURL($item['owner-link'], false);
844 if (empty($item_profile)) {
848 $profile_uid = User::getIdForURL($item_profile['url']);
850 foreach (['to', 'cc', 'bto', 'bcc'] as $element) {
851 if (empty($permissions[$element])) {
855 $blindcopy = in_array($element, ['bto', 'bcc']);
857 foreach ($permissions[$element] as $receiver) {
858 if (empty($receiver) || Network::isUrlBlocked($receiver)) {
862 if ($item_profile && ($receiver == $item_profile['followers']) && ($uid == $profile_uid)) {
863 $inboxes = array_merge($inboxes, self::fetchTargetInboxesforUser($uid, $personal, self::isAPPost($last_id)));
865 $profile = APContact::getByURL($receiver, false);
866 if (!empty($profile)) {
867 $contact = Contact::getByURLForUser($receiver, $uid, false, ['id']);
869 if (empty($profile['sharedinbox']) || $personal || $blindcopy || Contact::isLocal($receiver)) {
870 $target = $profile['inbox'];
872 $target = $profile['sharedinbox'];
874 if (!self::archivedInbox($target)) {
875 $inboxes[$target][] = $contact['id'] ?? 0;
886 * Creates an array in the structure of the item table for a given mail id
888 * @param integer $mail_id
893 public static function ItemArrayFromMail($mail_id, $use_title = false)
895 $mail = DBA::selectFirst('mail', [], ['id' => $mail_id]);
896 if (!DBA::isResult($mail)) {
900 $reply = DBA::selectFirst('mail', ['uri', 'uri-id', 'from-url'], ['parent-uri' => $mail['parent-uri'], 'reply' => false]);
901 if (!DBA::isResult($reply)) {
905 // Making the post more compatible for Mastodon by:
906 // - Making it a note and not an article (no title)
907 // - Moving the title into the "summary" field that is used as a "content warning"
910 $mail['body'] = '[abstract]' . $mail['title'] . "[/abstract]\n" . $mail['body'];
914 $mail['author-link'] = $mail['owner-link'] = $mail['from-url'];
915 $mail['owner-id'] = $mail['author-id'];
916 $mail['allow_cid'] = '<'.$mail['contact-id'].'>';
917 $mail['allow_gid'] = '';
918 $mail['deny_cid'] = '';
919 $mail['deny_gid'] = '';
920 $mail['private'] = Item::PRIVATE;
921 $mail['deleted'] = false;
922 $mail['edited'] = $mail['created'];
923 $mail['plink'] = DI::baseUrl() . '/message/' . $mail['id'];
924 $mail['parent-uri'] = $reply['uri'];
925 $mail['parent-uri-id'] = $reply['uri-id'];
926 $mail['parent-author-id'] = Contact::getIdForURL($reply['from-url'], 0, false);
927 $mail['gravity'] = ($mail['reply'] ? GRAVITY_COMMENT: GRAVITY_PARENT);
928 $mail['event-type'] = '';
929 $mail['language'] = '';
936 * Creates an activity array for a given mail id
938 * @param integer $mail_id
939 * @param boolean $object_mode Is the activity item is used inside another object?
941 * @return array of activity
944 public static function createActivityFromMail($mail_id, $object_mode = false)
946 $mail = self::ItemArrayFromMail($mail_id);
950 $object = self::createNote($mail);
953 $data = ['@context' => ActivityPub::CONTEXT];
958 $data['id'] = $mail['uri'] . '/Create';
959 $data['type'] = 'Create';
960 $data['actor'] = $mail['author-link'];
961 $data['published'] = DateTimeFormat::utc($mail['created'] . '+00:00', DateTimeFormat::ATOM);
962 $data['instrument'] = self::getService();
963 $data = array_merge($data, self::createPermissionBlockForItem($mail, true));
965 if (empty($data['to']) && !empty($data['cc'])) {
966 $data['to'] = $data['cc'];
969 if (empty($data['to']) && !empty($data['bcc'])) {
970 $data['to'] = $data['bcc'];
976 $object['to'] = $data['to'];
977 $object['tag'] = [['type' => 'Mention', 'href' => $object['to'][0], 'name' => '']];
979 unset($object['cc']);
980 unset($object['bcc']);
982 $data['directMessage'] = true;
984 $data['object'] = $object;
986 $owner = User::getOwnerDataById($mail['uid']);
988 if (!$object_mode && !empty($owner)) {
989 return LDSignature::sign($data, $owner);
996 * Returns the activity type of a given item
1000 * @return string with activity type
1001 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1002 * @throws \ImagickException
1004 private static function getTypeOfItem($item)
1008 // Only check for a reshare, if it is a real reshare and no quoted reshare
1009 if (strpos($item['body'], "[share") === 0) {
1010 $announce = self::getAnnounceArray($item);
1011 $reshared = !empty($announce);
1016 } elseif ($item['verb'] == Activity::POST) {
1017 if ($item['created'] == $item['edited']) {
1022 } elseif ($item['verb'] == Activity::LIKE) {
1024 } elseif ($item['verb'] == Activity::DISLIKE) {
1026 } elseif ($item['verb'] == Activity::ATTEND) {
1028 } elseif ($item['verb'] == Activity::ATTENDNO) {
1030 } elseif ($item['verb'] == Activity::ATTENDMAYBE) {
1031 $type = 'TentativeAccept';
1032 } elseif ($item['verb'] == Activity::FOLLOW) {
1034 } elseif ($item['verb'] == Activity::TAG) {
1036 } elseif ($item['verb'] == Activity::ANNOUNCE) {
1046 * Creates the activity or fetches it from the cache
1048 * @param integer $item_id
1049 * @param boolean $force Force new cache entry
1051 * @return array with the activity
1052 * @throws \Exception
1054 public static function createCachedActivityFromItem($item_id, $force = false)
1056 $cachekey = 'APDelivery:createActivity:' . $item_id;
1059 $data = DI::cache()->get($cachekey);
1060 if (!is_null($data)) {
1065 $data = self::createActivityFromItem($item_id);
1067 DI::cache()->set($cachekey, $data, Duration::QUARTER_HOUR);
1072 * Creates an activity array for a given item id
1074 * @param integer $item_id
1075 * @param boolean $object_mode Is the activity item is used inside another object?
1077 * @return false|array
1078 * @throws \Exception
1080 public static function createActivityFromItem(int $item_id, bool $object_mode = false)
1082 Logger::info('Fetching activity', ['item' => $item_id]);
1083 $item = Post::selectFirst(Item::DELIVER_FIELDLIST, ['id' => $item_id, 'parent-network' => Protocol::NATIVE_SUPPORT]);
1084 if (!DBA::isResult($item)) {
1088 if (empty($item['uri-id'])) {
1089 Logger::warning('Item without uri-id', ['item' => $item]);
1093 if (!$item['deleted']) {
1094 $condition = ['item-uri' => $item['uri'], 'protocol' => Conversation::PARCEL_ACTIVITYPUB];
1095 $conversation = DBA::selectFirst('conversation', ['source'], $condition);
1096 if (!$item['origin'] && DBA::isResult($conversation)) {
1097 $data = json_decode($conversation['source'], true);
1098 if (!empty($data['type'])) {
1099 if (in_array($data['type'], ['Create', 'Update'])) {
1101 unset($data['@context']);
1102 unset($data['signature']);
1104 Logger::info('Return stored conversation', ['item' => $item_id]);
1106 } elseif (in_array('as:' . $data['type'], Receiver::CONTENT_TYPES)) {
1107 if (!empty($data['@context'])) {
1108 $context = $data['@context'];
1109 unset($data['@context']);
1111 unset($data['actor']);
1118 $type = self::getTypeOfItem($item);
1120 if (!$object_mode) {
1121 $data = ['@context' => $context ?? ActivityPub::CONTEXT];
1123 if ($item['deleted'] && ($item['gravity'] == GRAVITY_ACTIVITY)) {
1125 } elseif ($item['deleted']) {
1132 if ($type == 'Delete') {
1133 $data['id'] = Item::newURI($item['uid'], $item['guid']) . '/' . $type;;
1134 } elseif (($item['gravity'] == GRAVITY_ACTIVITY) && ($type != 'Undo')) {
1135 $data['id'] = $item['uri'];
1137 $data['id'] = $item['uri'] . '/' . $type;
1140 $data['type'] = $type;
1142 if (($type != 'Announce') || ($item['gravity'] != GRAVITY_PARENT)) {
1143 $data['actor'] = $item['author-link'];
1145 $data['actor'] = $item['owner-link'];
1148 $data['published'] = DateTimeFormat::utc($item['created'] . '+00:00', DateTimeFormat::ATOM);
1150 $data['instrument'] = self::getService();
1152 $data = array_merge($data, self::createPermissionBlockForItem($item, false));
1154 if (in_array($data['type'], ['Create', 'Update', 'Delete'])) {
1155 $data['object'] = $object ?? self::createNote($item);
1156 } elseif ($data['type'] == 'Add') {
1157 $data = self::createAddTag($item, $data);
1158 } elseif ($data['type'] == 'Announce') {
1159 if ($item['verb'] == ACTIVITY::ANNOUNCE) {
1160 $data['object'] = $item['thr-parent'];
1162 $data = self::createAnnounce($item, $data);
1164 } elseif ($data['type'] == 'Follow') {
1165 $data['object'] = $item['parent-uri'];
1166 } elseif ($data['type'] == 'Undo') {
1167 $data['object'] = self::createActivityFromItem($item_id, true);
1169 $data['diaspora:guid'] = $item['guid'];
1170 if (!empty($item['signed_text'])) {
1171 $data['diaspora:like'] = $item['signed_text'];
1173 $data['object'] = $item['thr-parent'];
1176 if (!empty($item['contact-uid'])) {
1177 $uid = $item['contact-uid'];
1179 $uid = $item['uid'];
1182 $owner = User::getOwnerDataById($uid);
1184 Logger::info('Fetched activity', ['item' => $item_id, 'uid' => $uid]);
1186 // We don't sign if we aren't the actor. This is important for relaying content especially for forums
1187 if (!$object_mode && !empty($owner) && ($data['actor'] == $owner['url'])) {
1188 return LDSignature::sign($data, $owner);
1193 /// @todo Create "conversation" entry
1197 * Creates a location entry for a given item array
1199 * @param array $item
1201 * @return array with location array
1203 private static function createLocation($item)
1205 $location = ['type' => 'Place'];
1207 if (!empty($item['location'])) {
1208 $location['name'] = $item['location'];
1213 if (empty($item['coord'])) {
1214 $coord = Map::getCoordinates($item['location']);
1216 $coords = explode(' ', $item['coord']);
1217 if (count($coords) == 2) {
1218 $coord = ['lat' => $coords[0], 'lon' => $coords[1]];
1222 if (!empty($coord['lat']) && !empty($coord['lon'])) {
1223 $location['latitude'] = $coord['lat'];
1224 $location['longitude'] = $coord['lon'];
1231 * Returns a tag array for a given item array
1233 * @param array $item
1235 * @return array of tags
1236 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1238 private static function createTagList($item)
1242 $terms = Tag::getByURIId($item['uri-id'], [Tag::HASHTAG, Tag::MENTION, Tag::IMPLICIT_MENTION, Tag::EXCLUSIVE_MENTION]);
1243 foreach ($terms as $term) {
1244 if ($term['type'] == Tag::HASHTAG) {
1245 $url = DI::baseUrl() . '/search?tag=' . urlencode($term['name']);
1246 $tags[] = ['type' => 'Hashtag', 'href' => $url, 'name' => '#' . $term['name']];
1248 $contact = Contact::getByURL($term['url'], false, ['addr']);
1249 if (empty($contact)) {
1252 if (!empty($contact['addr'])) {
1253 $mention = '@' . $contact['addr'];
1255 $mention = '@' . $term['url'];
1258 $tags[] = ['type' => 'Mention', 'href' => $term['url'], 'name' => $mention];
1262 $announce = self::getAnnounceArray($item);
1263 // Mention the original author upon commented reshares
1264 if (!empty($announce['comment'])) {
1265 $tags[] = ['type' => 'Mention', 'href' => $announce['actor']['url'], 'name' => '@' . $announce['actor']['addr']];
1272 * Adds attachment data to the JSON document
1274 * @param array $item Data of the item that is to be posted
1275 * @param string $type Object type
1277 * @return array with attachment data
1278 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1280 private static function createAttachmentList($item, $type)
1284 $uriids = [$item['uri-id']];
1285 $shared = BBCode::fetchShareAttributes($item['body']);
1286 if (!empty($shared['guid'])) {
1287 $shared_item = Post::selectFirst(['uri-id'], ['guid' => $shared['guid']]);
1288 if (!empty($shared_item['uri-id'])) {
1289 $uriids[] = $shared_item['uri-id'];
1294 foreach ($uriids as $uriid) {
1295 foreach (Post\Media::getByURIId($uriid, [Post\Media::AUDIO, Post\Media::IMAGE, Post\Media::VIDEO, Post\Media::DOCUMENT, Post\Media::TORRENT]) as $attachment) {
1296 if (in_array($attachment['url'], $urls)) {
1299 $urls[] = $attachment['url'];
1301 $attach = ['type' => 'Document',
1302 'mediaType' => $attachment['mimetype'],
1303 'url' => $attachment['url'],
1304 'name' => $attachment['description']];
1306 if (!empty($attachment['height'])) {
1307 $attach['height'] = $attachment['height'];
1310 if (!empty($attachment['width'])) {
1311 $attach['width'] = $attachment['width'];
1314 if (!empty($attachment['preview'])) {
1315 $attach['image'] = $attachment['preview'];
1318 $attachments[] = $attach;
1322 return $attachments;
1326 * Callback function to replace a Friendica style mention in a mention for a summary
1328 * @param array $match Matching values for the callback
1329 * @return string Replaced mention
1330 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1332 private static function mentionAddrCallback($match)
1334 if (empty($match[1])) {
1338 $data = Contact::getByURL($match[1], false, ['addr']);
1339 if (empty($data['addr'])) {
1343 return '@' . $data['addr'];
1347 * Remove image elements since they are added as attachment
1349 * @param string $body
1351 * @return string with removed images
1353 private static function removePictures($body)
1355 // Simplify image codes
1356 $body = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '[img]$3[/img]', $body);
1357 $body = preg_replace("/\[img\=(.*?)\](.*?)\[\/img\]/ism", '[img]$1[/img]', $body);
1359 // Now remove local links
1360 $body = preg_replace_callback(
1361 '/\[url=([^\[\]]*)\]\[img\](.*)\[\/img\]\[\/url\]/Usi',
1363 // We remove the link when it is a link to a local photo page
1364 if (Photo::isLocalPage($match[1])) {
1367 // otherwise we just return the link
1368 return '[url]' . $match[1] . '[/url]';
1373 // Remove all pictures
1374 $body = preg_replace("/\[img\]([^\[\]]*)\[\/img\]/Usi", '', $body);
1380 * Fetches the "context" value for a givem item array from the "conversation" table
1382 * @param array $item
1384 * @return string with context url
1385 * @throws \Exception
1387 private static function fetchContextURLForItem($item)
1389 $conversation = DBA::selectFirst('conversation', ['conversation-href', 'conversation-uri'], ['item-uri' => $item['parent-uri']]);
1390 if (DBA::isResult($conversation) && !empty($conversation['conversation-href'])) {
1391 $context_uri = $conversation['conversation-href'];
1392 } elseif (DBA::isResult($conversation) && !empty($conversation['conversation-uri'])) {
1393 $context_uri = $conversation['conversation-uri'];
1395 $context_uri = $item['parent-uri'] . '#context';
1397 return $context_uri;
1401 * Returns if the post contains sensitive content ("nsfw")
1403 * @param integer $uri_id
1406 * @throws \Exception
1408 private static function isSensitive($uri_id)
1410 return DBA::exists('tag-view', ['uri-id' => $uri_id, 'name' => 'nsfw']);
1414 * Creates event data
1416 * @param array $item
1418 * @return array with the event data
1419 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1421 private static function createEvent($item)
1424 $event['name'] = $item['event-summary'];
1425 $event['content'] = BBCode::convertForUriId($item['uri-id'], $item['event-desc'], BBCode::ACTIVITYPUB);
1426 $event['startTime'] = DateTimeFormat::utc($item['event-start'], 'c');
1428 if (!$item['event-nofinish']) {
1429 $event['endTime'] = DateTimeFormat::utc($item['event-finish'], 'c');
1432 if (!empty($item['event-location'])) {
1433 $item['location'] = $item['event-location'];
1434 $event['location'] = self::createLocation($item);
1437 // 2021.12: Backward compatibility value, all the events now "adjust" to the viewer timezone
1438 $event['dfrn:adjust'] = true;
1444 * Creates a note/article object array
1446 * @param array $item
1448 * @return array with the object data
1449 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1450 * @throws \ImagickException
1452 public static function createNote($item)
1458 if ($item['event-type'] == 'event') {
1460 } elseif (!empty($item['title'])) {
1466 if ($item['deleted']) {
1467 $type = 'Tombstone';
1471 $data['id'] = $item['uri'];
1472 $data['type'] = $type;
1474 if ($item['deleted']) {
1478 $data['summary'] = BBCode::toPlaintext(BBCode::getAbstract($item['body'], Protocol::ACTIVITYPUB));
1480 if ($item['uri'] != $item['thr-parent']) {
1481 $data['inReplyTo'] = $item['thr-parent'];
1483 $data['inReplyTo'] = null;
1486 $data['diaspora:guid'] = $item['guid'];
1487 $data['published'] = DateTimeFormat::utc($item['created'] . '+00:00', DateTimeFormat::ATOM);
1489 if ($item['created'] != $item['edited']) {
1490 $data['updated'] = DateTimeFormat::utc($item['edited'] . '+00:00', DateTimeFormat::ATOM);
1493 $data['url'] = $item['plink'];
1494 $data['attributedTo'] = $item['author-link'];
1495 $data['sensitive'] = self::isSensitive($item['uri-id']);
1496 $data['context'] = self::fetchContextURLForItem($item);
1498 if (!empty($item['title'])) {
1499 $data['name'] = BBCode::toPlaintext($item['title'], false);
1502 $permission_block = self::createPermissionBlockForItem($item, false);
1504 $body = $item['body'];
1506 if ($type == 'Note') {
1507 $body = $item['raw-body'] ?? self::removePictures($body);
1511 * @todo Improve the automated summary
1512 * This part is currently deactivated. The automated summary seems to be more
1513 * confusing than helping. But possibly we will find a better way.
1514 * So the code is left here for now as a reminder
1516 * } elseif (($type == 'Article') && empty($data['summary'])) {
1517 * $regexp = "/[@!]\[url\=([^\[\]]*)\].*?\[\/url\]/ism";
1518 * $summary = preg_replace_callback($regexp, ['self', 'mentionAddrCallback'], $body);
1519 * $data['summary'] = BBCode::toPlaintext(Plaintext::shorten(self::removePictures($summary), 1000));
1523 if (empty($item['uid']) || !Feature::isEnabled($item['uid'], 'explicit_mentions')) {
1524 $body = self::prependMentions($body, $item['uri-id'], $item['author-link']);
1527 if ($type == 'Event') {
1528 $data = array_merge($data, self::createEvent($item));
1530 $body = BBCode::setMentionsToNicknames($body);
1532 $data['content'] = BBCode::convertForUriId($item['uri-id'], $body, BBCode::ACTIVITYPUB);
1535 // The regular "content" field does contain a minimized HTML. This is done since systems like
1536 // Mastodon has got problems with - for example - embedded pictures.
1537 // The contentMap does contain the unmodified HTML.
1538 $language = self::getLanguage($item);
1539 if (!empty($language)) {
1540 $richbody = BBCode::setMentionsToNicknames($item['body'] ?? '');
1541 $richbody = BBCode::removeAttachment($richbody);
1543 $data['contentMap'][$language] = BBCode::convertForUriId($item['uri-id'], $richbody, BBCode::EXTERNAL);
1546 $data['source'] = ['content' => $item['body'], 'mediaType' => "text/bbcode"];
1548 if (!empty($item['signed_text']) && ($item['uri'] != $item['thr-parent'])) {
1549 $data['diaspora:comment'] = $item['signed_text'];
1552 $data['attachment'] = self::createAttachmentList($item, $type);
1553 $data['tag'] = self::createTagList($item);
1555 if (empty($data['location']) && (!empty($item['coord']) || !empty($item['location']))) {
1556 $data['location'] = self::createLocation($item);
1559 if (!empty($item['app'])) {
1560 $data['generator'] = ['type' => 'Application', 'name' => $item['app']];
1563 $data = array_merge($data, $permission_block);
1569 * Fetches the language from the post, the user or the system.
1571 * @param array $item
1573 * @return string language string
1575 private static function getLanguage(array $item)
1577 // Try to fetch the language from the post itself
1578 if (!empty($item['language'])) {
1579 $languages = array_keys(json_decode($item['language'], true));
1580 if (!empty($languages[0])) {
1581 return $languages[0];
1585 // Otherwise use the user's language
1586 if (!empty($item['uid'])) {
1587 $user = DBA::selectFirst('user', ['language'], ['uid' => $item['uid']]);
1588 if (!empty($user['language'])) {
1589 return $user['language'];
1593 // And finally just use the system language
1594 return DI::config()->get('system', 'language');
1598 * Creates an an "add tag" entry
1600 * @param array $item
1601 * @param array $data activity data
1603 * @return array with activity data for adding tags
1604 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1605 * @throws \ImagickException
1607 private static function createAddTag($item, $data)
1609 $object = XML::parseString($item['object']);
1610 $target = XML::parseString($item["target"]);
1612 $data['diaspora:guid'] = $item['guid'];
1613 $data['actor'] = $item['author-link'];
1614 $data['target'] = (string)$target->id;
1615 $data['summary'] = BBCode::toPlaintext($item['body']);
1616 $data['object'] = ['id' => (string)$object->id, 'type' => 'tag', 'name' => (string)$object->title, 'content' => (string)$object->content];
1622 * Creates an announce object entry
1624 * @param array $item
1625 * @param array $data activity data
1627 * @return array with activity data
1628 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1629 * @throws \ImagickException
1631 private static function createAnnounce($item, $data)
1633 $orig_body = $item['body'];
1634 $announce = self::getAnnounceArray($item);
1635 if (empty($announce)) {
1636 $data['type'] = 'Create';
1637 $data['object'] = self::createNote($item);
1641 if (empty($announce['comment'])) {
1642 // Pure announce, without a quote
1643 $data['type'] = 'Announce';
1644 $data['object'] = $announce['object']['uri'];
1649 $data['type'] = 'Create';
1650 $item['body'] = $announce['comment'] . "\n" . $announce['object']['plink'];
1651 $data['object'] = self::createNote($item);
1653 /// @todo Finally descide how to implement this in AP. This is a possible way:
1654 $data['object']['attachment'][] = self::createNote($announce['object']);
1656 $data['object']['source']['content'] = $orig_body;
1661 * Return announce related data if the item is an annunce
1663 * @param array $item
1667 public static function getAnnounceArray($item)
1669 $reshared = Item::getShareArray($item);
1670 if (empty($reshared['guid'])) {
1674 $reshared_item = Post::selectFirst(Item::DELIVER_FIELDLIST, ['guid' => $reshared['guid']]);
1675 if (!DBA::isResult($reshared_item)) {
1679 if (!in_array($reshared_item['network'], [Protocol::ACTIVITYPUB, Protocol::DFRN])) {
1683 $profile = APContact::getByURL($reshared_item['author-link'], false);
1684 if (empty($profile)) {
1688 return ['object' => $reshared_item, 'actor' => $profile, 'comment' => $reshared['comment']];
1692 * Checks if the provided item array is an announce
1694 * @param array $item
1698 public static function isAnnounce($item)
1700 if (!empty($item['verb']) && ($item['verb'] == Activity::ANNOUNCE)) {
1704 $announce = self::getAnnounceArray($item);
1705 if (empty($announce)) {
1709 return empty($announce['comment']);
1713 * Creates an activity id for a given contact id
1715 * @param integer $cid Contact ID of target
1717 * @return bool|string activity id
1719 public static function activityIDFromContact($cid)
1721 $contact = DBA::selectFirst('contact', ['uid', 'id', 'created'], ['id' => $cid]);
1722 if (!DBA::isResult($contact)) {
1726 $hash = hash('ripemd128', $contact['uid'].'-'.$contact['id'].'-'.$contact['created']);
1727 $uuid = substr($hash, 0, 8). '-' . substr($hash, 8, 4) . '-' . substr($hash, 12, 4) . '-' . substr($hash, 16, 4) . '-' . substr($hash, 20, 12);
1728 return DI::baseUrl() . '/activity/' . $uuid;
1732 * Transmits a contact suggestion to a given inbox
1734 * @param integer $uid User ID
1735 * @param string $inbox Target inbox
1736 * @param integer $suggestion_id Suggestion ID
1738 * @return boolean was the transmission successful?
1739 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1741 public static function sendContactSuggestion($uid, $inbox, $suggestion_id)
1743 $owner = User::getOwnerDataById($uid);
1745 $suggestion = DI::fsuggest()->selectOneById($suggestion_id);
1747 $data = ['@context' => ActivityPub::CONTEXT,
1748 'id' => DI::baseUrl() . '/activity/' . System::createGUID(),
1749 'type' => 'Announce',
1750 'actor' => $owner['url'],
1751 'object' => $suggestion->url,
1752 'content' => $suggestion->note,
1753 'instrument' => self::getService(),
1754 'to' => [ActivityPub::PUBLIC_COLLECTION],
1757 $signed = LDSignature::sign($data, $owner);
1759 Logger::info('Deliver profile deletion for user ' . $uid . ' to ' . $inbox . ' via ActivityPub');
1760 return HTTPSignature::transmit($signed, $inbox, $uid);
1764 * Transmits a profile relocation to a given inbox
1766 * @param integer $uid User ID
1767 * @param string $inbox Target inbox
1769 * @return boolean was the transmission successful?
1770 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1772 public static function sendProfileRelocation($uid, $inbox)
1774 $owner = User::getOwnerDataById($uid);
1776 $data = ['@context' => ActivityPub::CONTEXT,
1777 'id' => DI::baseUrl() . '/activity/' . System::createGUID(),
1778 'type' => 'dfrn:relocate',
1779 'actor' => $owner['url'],
1780 'object' => $owner['url'],
1781 'published' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
1782 'instrument' => self::getService(),
1783 'to' => [ActivityPub::PUBLIC_COLLECTION],
1786 $signed = LDSignature::sign($data, $owner);
1788 Logger::info('Deliver profile relocation for user ' . $uid . ' to ' . $inbox . ' via ActivityPub');
1789 return HTTPSignature::transmit($signed, $inbox, $uid);
1793 * Transmits a profile deletion to a given inbox
1795 * @param integer $uid User ID
1796 * @param string $inbox Target inbox
1798 * @return boolean was the transmission successful?
1799 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1801 public static function sendProfileDeletion($uid, $inbox)
1803 $owner = User::getOwnerDataById($uid);
1805 if (empty($owner)) {
1806 Logger::error('No owner data found, the deletion message cannot be processed.', ['user' => $uid]);
1810 if (empty($owner['uprvkey'])) {
1811 Logger::error('No private key for owner found, the deletion message cannot be processed.', ['user' => $uid]);
1815 $data = ['@context' => ActivityPub::CONTEXT,
1816 'id' => DI::baseUrl() . '/activity/' . System::createGUID(),
1818 'actor' => $owner['url'],
1819 'object' => $owner['url'],
1820 'published' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
1821 'instrument' => self::getService(),
1822 'to' => [ActivityPub::PUBLIC_COLLECTION],
1825 $signed = LDSignature::sign($data, $owner);
1827 Logger::info('Deliver profile deletion for user ' . $uid . ' to ' . $inbox . ' via ActivityPub');
1828 return HTTPSignature::transmit($signed, $inbox, $uid);
1832 * Transmits a profile change to a given inbox
1834 * @param integer $uid User ID
1835 * @param string $inbox Target inbox
1837 * @return boolean was the transmission successful?
1838 * @throws HTTPException\InternalServerErrorException
1839 * @throws HTTPException\NotFoundException
1840 * @throws \ImagickException
1842 public static function sendProfileUpdate(int $uid, string $inbox): bool
1844 $owner = User::getOwnerDataById($uid);
1845 $profile = APContact::getByURL($owner['url']);
1847 $data = ['@context' => ActivityPub::CONTEXT,
1848 'id' => DI::baseUrl() . '/activity/' . System::createGUID(),
1850 'actor' => $owner['url'],
1851 'object' => self::getProfile($uid),
1852 'published' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
1853 'instrument' => self::getService(),
1854 'to' => [$profile['followers']],
1857 $signed = LDSignature::sign($data, $owner);
1859 Logger::info('Deliver profile update for user ' . $uid . ' to ' . $inbox . ' via ActivityPub');
1860 return HTTPSignature::transmit($signed, $inbox, $uid);
1864 * Transmits a given activity to a target
1866 * @param string $activity Type name
1867 * @param string $target Target profile
1868 * @param integer $uid User ID
1870 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1871 * @throws \ImagickException
1872 * @throws \Exception
1874 public static function sendActivity($activity, $target, $uid, $id = '')
1876 $profile = APContact::getByURL($target);
1877 if (empty($profile['inbox'])) {
1878 Logger::warning('No inbox found for target', ['target' => $target, 'profile' => $profile]);
1882 $owner = User::getOwnerDataById($uid);
1885 $id = DI::baseUrl() . '/activity/' . System::createGUID();
1888 $data = ['@context' => ActivityPub::CONTEXT,
1890 'type' => $activity,
1891 'actor' => $owner['url'],
1892 'object' => $profile['url'],
1893 'instrument' => self::getService(),
1894 'to' => [$profile['url']]];
1896 Logger::info('Sending activity ' . $activity . ' to ' . $target . ' for user ' . $uid);
1898 $signed = LDSignature::sign($data, $owner);
1899 return HTTPSignature::transmit($signed, $profile['inbox'], $uid);
1903 * Transmits a "follow object" activity to a target
1904 * This is a preparation for sending automated "follow" requests when receiving "Announce" messages
1906 * @param string $object Object URL
1907 * @param string $target Target profile
1908 * @param integer $uid User ID
1910 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1911 * @throws \ImagickException
1912 * @throws \Exception
1914 public static function sendFollowObject($object, $target, $uid = 0)
1916 $profile = APContact::getByURL($target);
1917 if (empty($profile['inbox'])) {
1918 Logger::warning('No inbox found for target', ['target' => $target, 'profile' => $profile]);
1923 // Fetch the list of administrators
1924 $admin_mail = explode(',', str_replace(' ', '', DI::config()->get('config', 'admin_email')));
1926 // We need to use some user as a sender. It doesn't care who it will send. We will use an administrator account.
1927 $condition = ['verified' => true, 'blocked' => false, 'account_removed' => false, 'account_expired' => false, 'email' => $admin_mail];
1928 $first_user = DBA::selectFirst('user', ['uid'], $condition);
1929 $uid = $first_user['uid'];
1932 $condition = ['verb' => Activity::FOLLOW, 'uid' => 0, 'parent-uri' => $object,
1933 'author-id' => Contact::getPublicIdByUserId($uid)];
1934 if (Post::exists($condition)) {
1935 Logger::info('Follow for ' . $object . ' for user ' . $uid . ' does already exist.');
1939 $owner = User::getOwnerDataById($uid);
1941 $data = ['@context' => ActivityPub::CONTEXT,
1942 'id' => DI::baseUrl() . '/activity/' . System::createGUID(),
1944 'actor' => $owner['url'],
1945 'object' => $object,
1946 'instrument' => self::getService(),
1947 'to' => [$profile['url']]];
1949 Logger::info('Sending follow ' . $object . ' to ' . $target . ' for user ' . $uid);
1951 $signed = LDSignature::sign($data, $owner);
1952 return HTTPSignature::transmit($signed, $profile['inbox'], $uid);
1956 * Transmit a message that the contact request had been accepted
1958 * @param string $target Target profile
1960 * @param integer $uid User ID
1961 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1962 * @throws \ImagickException
1964 public static function sendContactAccept($target, $id, $uid)
1966 $profile = APContact::getByURL($target);
1967 if (empty($profile['inbox'])) {
1968 Logger::warning('No inbox found for target', ['target' => $target, 'profile' => $profile]);
1972 $owner = User::getOwnerDataById($uid);
1973 $data = ['@context' => ActivityPub::CONTEXT,
1974 'id' => DI::baseUrl() . '/activity/' . System::createGUID(),
1976 'actor' => $owner['url'],
1978 'id' => (string)$id,
1980 'actor' => $profile['url'],
1981 'object' => $owner['url']
1983 'instrument' => self::getService(),
1984 'to' => [$profile['url']]];
1986 Logger::debug('Sending accept to ' . $target . ' for user ' . $uid . ' with id ' . $id);
1988 $signed = LDSignature::sign($data, $owner);
1989 HTTPSignature::transmit($signed, $profile['inbox'], $uid);
1993 * Reject a contact request or terminates the contact relation
1995 * @param string $target Target profile
1997 * @param integer $uid User ID
1998 * @return bool Operation success
1999 * @throws HTTPException\InternalServerErrorException
2000 * @throws \ImagickException
2002 public static function sendContactReject($target, $id, $uid): bool
2004 $profile = APContact::getByURL($target);
2005 if (empty($profile['inbox'])) {
2006 Logger::warning('No inbox found for target', ['target' => $target, 'profile' => $profile]);
2010 $owner = User::getOwnerDataById($uid);
2011 $data = ['@context' => ActivityPub::CONTEXT,
2012 'id' => DI::baseUrl() . '/activity/' . System::createGUID(),
2014 'actor' => $owner['url'],
2016 'id' => (string)$id,
2018 'actor' => $profile['url'],
2019 'object' => $owner['url']
2021 'instrument' => self::getService(),
2022 'to' => [$profile['url']]];
2024 Logger::debug('Sending reject to ' . $target . ' for user ' . $uid . ' with id ' . $id);
2026 $signed = LDSignature::sign($data, $owner);
2027 return HTTPSignature::transmit($signed, $profile['inbox'], $uid);
2031 * Transmits a message that we don't want to follow this contact anymore
2033 * @param string $target Target profile
2034 * @param integer $uid User ID
2035 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2036 * @throws \ImagickException
2037 * @throws \Exception
2038 * @return bool success
2040 public static function sendContactUndo($target, $cid, $uid)
2042 $profile = APContact::getByURL($target);
2043 if (empty($profile['inbox'])) {
2044 Logger::warning('No inbox found for target', ['target' => $target, 'profile' => $profile]);
2048 $object_id = self::activityIDFromContact($cid);
2049 if (empty($object_id)) {
2053 $id = DI::baseUrl() . '/activity/' . System::createGUID();
2055 $owner = User::getOwnerDataById($uid);
2056 $data = ['@context' => ActivityPub::CONTEXT,
2059 'actor' => $owner['url'],
2060 'object' => ['id' => $object_id, 'type' => 'Follow',
2061 'actor' => $owner['url'],
2062 'object' => $profile['url']],
2063 'instrument' => self::getService(),
2064 'to' => [$profile['url']]];
2066 Logger::info('Sending undo to ' . $target . ' for user ' . $uid . ' with id ' . $id);
2068 $signed = LDSignature::sign($data, $owner);
2069 return HTTPSignature::transmit($signed, $profile['inbox'], $uid);
2072 private static function prependMentions($body, int $uriid, string $authorLink)
2076 foreach (Tag::getByURIId($uriid, [Tag::IMPLICIT_MENTION]) as $tag) {
2077 $profile = Contact::getByURL($tag['url'], false, ['addr', 'contact-type', 'nick']);
2078 if (!empty($profile['addr'])
2079 && $profile['contact-type'] != Contact::TYPE_COMMUNITY
2080 && !strstr($body, $profile['addr'])
2081 && !strstr($body, $tag['url'])
2082 && $tag['url'] !== $authorLink
2084 $mentions[] = '@[url=' . $tag['url'] . ']' . $profile['nick'] . '[/url]';
2088 $mentions[] = $body;
2090 return implode(' ', $mentions);