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\Profile;
40 use Friendica\Model\Tag;
41 use Friendica\Model\User;
42 use Friendica\Network\HTTPException;
43 use Friendica\Protocol\Activity;
44 use Friendica\Protocol\ActivityPub;
45 use Friendica\Protocol\Relay;
46 use Friendica\Util\DateTimeFormat;
47 use Friendica\Util\HTTPSignature;
48 use Friendica\Util\JsonLD;
49 use Friendica\Util\LDSignature;
50 use Friendica\Util\Map;
51 use Friendica\Util\Network;
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
154 * @return array of owners
157 public static function getContacts($owner, $rel, $module, $page = null)
161 'uid' => $owner['uid'],
170 $condition = DBA::mergeConditions($parameters, ["`url` IN (SELECT `url` FROM `apcontact`)"]);
172 $total = DBA::count('contact', $condition);
174 $modulePath = '/' . $module . '/';
176 $data = ['@context' => ActivityPub::CONTEXT];
177 $data['id'] = DI::baseUrl() . $modulePath . $owner['nickname'];
178 $data['type'] = 'OrderedCollection';
179 $data['totalItems'] = $total;
181 // When we hide our friends we will only show the pure number but don't allow more.
182 $profile = Profile::getByUID($owner['uid']);
183 if (!empty($profile['hide-friends'])) {
188 $data['first'] = DI::baseUrl() . $modulePath . $owner['nickname'] . '?page=1';
190 $data['type'] = 'OrderedCollectionPage';
193 $contacts = DBA::select('contact', ['url'], $condition, ['limit' => [($page - 1) * 100, 100]]);
194 while ($contact = DBA::fetch($contacts)) {
195 $list[] = $contact['url'];
197 DBA::close($contacts);
200 $data['next'] = DI::baseUrl() . $modulePath . $owner['nickname'] . '?page=' . ($page + 1);
203 $data['partOf'] = DI::baseUrl() . $modulePath . $owner['nickname'];
205 $data['orderedItems'] = $list;
212 * Public posts for the given owner
214 * @param array $owner Owner array
215 * @param integer $page Page number
216 * @param string $requester URL of requesting account
218 * @return array of posts
219 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
220 * @throws \ImagickException
222 public static function getOutbox($owner, $page = null, $requester = '')
224 $condition = ['private' => [Item::PUBLIC, Item::UNLISTED]];
226 if (!empty($requester)) {
227 $requester_id = Contact::getIdForURL($requester, $owner['uid']);
228 if (!empty($requester_id)) {
229 $permissionSets = DI::permissionSet()->selectByContactId($requester_id, $owner['uid']);
230 if (!empty($permissionSets)) {
231 $condition = ['psid' => array_merge($permissionSets->column('id'),
232 [DI::permissionSet()->selectPublicForUser($owner['uid'])])];
237 $condition = array_merge($condition,
238 ['uid' => $owner['uid'],
239 'author-id' => Contact::getIdForURL($owner['url'], 0, false),
240 'gravity' => [GRAVITY_PARENT, GRAVITY_COMMENT],
241 'network' => Protocol::FEDERATED,
242 'parent-network' => Protocol::FEDERATED,
247 $count = Post::count($condition);
249 $data = ['@context' => ActivityPub::CONTEXT];
250 $data['id'] = DI::baseUrl() . '/outbox/' . $owner['nickname'];
251 $data['type'] = 'OrderedCollection';
252 $data['totalItems'] = $count;
255 $data['first'] = DI::baseUrl() . '/outbox/' . $owner['nickname'] . '?page=1';
257 $data['type'] = 'OrderedCollectionPage';
260 $items = Post::select(['id'], $condition, ['limit' => [($page - 1) * 20, 20], 'order' => ['created' => true]]);
261 while ($item = Post::fetch($items)) {
262 $activity = self::createActivityFromItem($item['id'], true);
263 $activity['type'] = $activity['type'] == 'Update' ? 'Create' : $activity['type'];
265 // Only list "Create" activity objects here, no reshares
266 if (!empty($activity['object']) && ($activity['type'] == 'Create')) {
267 $list[] = $activity['object'];
273 $data['next'] = DI::baseUrl() . '/outbox/' . $owner['nickname'] . '?page=' . ($page + 1);
276 $data['partOf'] = DI::baseUrl() . '/outbox/' . $owner['nickname'];
278 $data['orderedItems'] = $list;
285 * Return the service array containing information the used software and it's url
287 * @return array with service data
289 private static function getService()
291 return ['type' => 'Service',
292 'name' => FRIENDICA_PLATFORM . " '" . FRIENDICA_CODENAME . "' " . FRIENDICA_VERSION . '-' . DB_UPDATE_VERSION,
293 'url' => DI::baseUrl()->get()];
297 * Return the ActivityPub profile of the given user
299 * @param int $uid User ID
300 * @return array with profile data
301 * @throws HTTPException\NotFoundException
302 * @throws HTTPException\InternalServerErrorException
304 public static function getProfile(int $uid): array
306 $owner = User::getOwnerDataById($uid);
307 if (!isset($owner['id'])) {
308 DI::logger()->error('Unable to find owner data for uid', ['uid' => $uid, 'callstack' => System::callstack(20)]);
309 throw new HTTPException\NotFoundException('User not found.');
312 $data = ['@context' => ActivityPub::CONTEXT];
313 $data['id'] = $owner['url'];
315 if (!empty($owner['guid'])) {
316 $data['diaspora:guid'] = $owner['guid'];
319 $data['type'] = ActivityPub::ACCOUNT_TYPES[$owner['account-type']];
322 $data['following'] = DI::baseUrl() . '/following/' . $owner['nick'];
323 $data['followers'] = DI::baseUrl() . '/followers/' . $owner['nick'];
324 $data['inbox'] = DI::baseUrl() . '/inbox/' . $owner['nick'];
325 $data['outbox'] = DI::baseUrl() . '/outbox/' . $owner['nick'];
327 $data['inbox'] = DI::baseUrl() . '/friendica/inbox';
330 $data['preferredUsername'] = $owner['nick'];
331 $data['name'] = $owner['name'];
333 if (!empty($owner['country-name'] . $owner['region'] . $owner['locality'])) {
334 $data['vcard:hasAddress'] = ['@type' => 'vcard:Home', 'vcard:country-name' => $owner['country-name'],
335 'vcard:region' => $owner['region'], 'vcard:locality' => $owner['locality']];
338 if (!empty($owner['about'])) {
339 $data['summary'] = BBCode::convertForUriId($owner['uri-id'] ?? 0, $owner['about'], BBCode::EXTERNAL);
342 if (!empty($owner['xmpp']) || !empty($owner['matrix'])) {
343 $data['vcard:hasInstantMessage'] = [];
345 if (!empty($owner['xmpp'])) {
346 $data['vcard:hasInstantMessage'][] = 'xmpp:' . $owner['xmpp'];
348 if (!empty($owner['matrix'])) {
349 $data['vcard:hasInstantMessage'][] = 'matrix:' . $owner['matrix'];
353 $data['url'] = $owner['url'];
354 $data['manuallyApprovesFollowers'] = in_array($owner['page-flags'], [User::PAGE_FLAGS_NORMAL, User::PAGE_FLAGS_PRVGROUP]);
355 $data['discoverable'] = (bool)$owner['net-publish'];
356 $data['publicKey'] = ['id' => $owner['url'] . '#main-key',
357 'owner' => $owner['url'],
358 'publicKeyPem' => $owner['pubkey']];
359 $data['endpoints'] = ['sharedInbox' => DI::baseUrl() . '/inbox'];
360 $data['icon'] = ['type' => 'Image', 'url' => User::getAvatarUrl($owner)];
362 $resourceid = Photo::ridFromURI($owner['photo']);
363 if (!empty($resourceid)) {
364 $photo = Photo::selectFirst(['type'], ["resource-id" => $resourceid]);
365 if (!empty($photo['type'])) {
366 $data['icon']['mediaType'] = $photo['type'];
370 if (!empty($owner['header'])) {
371 $data['image'] = ['type' => 'Image', 'url' => Contact::getHeaderUrlForId($owner['id'], '', $owner['updated'])];
373 $resourceid = Photo::ridFromURI($owner['header']);
374 if (!empty($resourceid)) {
375 $photo = Photo::selectFirst(['type'], ["resource-id" => $resourceid]);
376 if (!empty($photo['type'])) {
377 $data['image']['mediaType'] = $photo['type'];
384 foreach (DI::profileField()->selectByContactId(0, $uid) as $profile_field) {
386 'type' => 'PropertyValue',
387 'name' => $profile_field->label,
388 'value' => BBCode::convertForUriId($owner['uri-id'], $profile_field->value)
392 if (!empty($custom_fields)) {
393 $data['attachment'] = $custom_fields;
396 $data['generator'] = self::getService();
398 // tags: https://kitty.town/@inmysocks/100656097926961126.json
403 * @param string $username
405 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
407 public static function getDeletedUser($username)
410 '@context' => ActivityPub::CONTEXT,
411 'id' => DI::baseUrl() . '/profile/' . $username,
412 'type' => 'Tombstone',
413 'published' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
414 'updated' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
415 'deleted' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
420 * Returns an array with permissions of a given item array
424 * @return array with permissions
425 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
426 * @throws \ImagickException
428 private static function fetchPermissionBlockFromConversation($item)
430 if (empty($item['thr-parent'])) {
434 $condition = ['item-uri' => $item['thr-parent'], 'protocol' => Conversation::PARCEL_ACTIVITYPUB];
435 $conversation = DBA::selectFirst('conversation', ['source'], $condition);
436 if (!DBA::isResult($conversation)) {
447 $activity = json_decode($conversation['source'], true);
449 $actor = JsonLD::fetchElement($activity, 'actor', 'id');
450 if (!empty($actor)) {
451 $permissions['to'][] = $actor;
452 $profile = APContact::getByURL($actor);
457 $item_profile = APContact::getByURL($item['author-link']);
458 $exclude[] = $item['author-link'];
460 if ($item['gravity'] == GRAVITY_PARENT) {
461 $exclude[] = $item['owner-link'];
464 foreach (['to', 'cc', 'bto', 'bcc'] as $element) {
465 if (empty($activity[$element])) {
468 if (is_string($activity[$element])) {
469 $activity[$element] = [$activity[$element]];
472 foreach ($activity[$element] as $receiver) {
473 if (empty($receiver)) {
477 if (!empty($profile['followers']) && $receiver == $profile['followers'] && !empty($item_profile['followers'])) {
478 $permissions[$element][] = $item_profile['followers'];
479 } elseif (!in_array($receiver, $exclude)) {
480 $permissions[$element][] = $receiver;
488 * Check if the given item id is from ActivityPub
490 * @param integer $item_id
491 * @return boolean "true" if the post is from ActivityPub
493 private static function isAPPost(int $item_id)
495 if (empty($item_id)) {
499 return Post::exists(['id' => $item_id, 'network' => Protocol::ACTIVITYPUB]);
503 * Creates an array of permissions from an item thread
505 * @param array $item Item array
506 * @param boolean $blindcopy addressing via "bcc" or "cc"?
507 * @param integer $last_id Last item id for adding receivers
508 * @param boolean $forum_post "true" means that we are sending content to a forum
510 * @return array with permission data
511 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
512 * @throws \ImagickException
514 private static function createPermissionBlockForItem($item, $blindcopy, $last_id = 0, $forum_post = false)
517 $last_id = $item['id'];
522 // Check if we should always deliver our stuff via BCC
523 if (!empty($item['uid'])) {
524 $profile = User::getOwnerDataById($item['uid']);
525 if (!empty($profile)) {
526 $always_bcc = $profile['hide-friends'];
530 if (DI::config()->get('system', 'ap_always_bcc')) {
534 if (self::isAnnounce($item) || DI::config()->get('debug', 'total_ap_delivery') || self::isAPPost($last_id)) {
535 // Will be activated in a later step
536 $networks = Protocol::FEDERATED;
538 // For now only send to these contacts:
539 $networks = [Protocol::ACTIVITYPUB, Protocol::OSTATUS];
542 $data = ['to' => [], 'cc' => [], 'bcc' => []];
544 if ($item['gravity'] == GRAVITY_PARENT) {
545 $actor_profile = APContact::getByURL($item['owner-link']);
547 $actor_profile = APContact::getByURL($item['author-link']);
552 $terms = Tag::getByURIId($item['uri-id'], [Tag::MENTION, Tag::IMPLICIT_MENTION, Tag::EXCLUSIVE_MENTION]);
554 if ($item['private'] != Item::PRIVATE) {
555 // Directly mention the original author upon a quoted reshare.
556 // Else just ensure that the original author receives the reshare.
557 $announce = self::getAnnounceArray($item);
558 if (!empty($announce['comment'])) {
559 $data['to'][] = $announce['actor']['url'];
560 } elseif (!empty($announce)) {
561 $data['cc'][] = $announce['actor']['url'];
564 $data = array_merge($data, self::fetchPermissionBlockFromConversation($item));
566 // Check if the item is completely public or unlisted
567 if ($item['private'] == Item::PUBLIC) {
568 $data['to'][] = ActivityPub::PUBLIC_COLLECTION;
570 $data['cc'][] = ActivityPub::PUBLIC_COLLECTION;
573 foreach ($terms as $term) {
574 $profile = APContact::getByURL($term['url'], false);
575 if (!empty($profile)) {
576 if ($term['type'] == Tag::EXCLUSIVE_MENTION) {
578 if (!empty($profile['followers']) && ($profile['type'] == 'Group')) {
579 $data['cc'][] = $profile['followers'];
582 $data['to'][] = $profile['url'];
586 $receiver_list = Item::enumeratePermissions($item, true);
588 foreach ($terms as $term) {
589 $cid = Contact::getIdForURL($term['url'], $item['uid']);
590 if (!empty($cid) && in_array($cid, $receiver_list)) {
591 $contact = DBA::selectFirst('contact', ['url', 'network', 'protocol', 'gsid'], ['id' => $cid, 'network' => Protocol::FEDERATED]);
592 if (!DBA::isResult($contact) || !self::isAPContact($contact, $networks)) {
596 if (!empty($profile = APContact::getByURL($contact['url'], false))) {
597 $data['to'][] = $profile['url'];
602 foreach ($receiver_list as $receiver) {
603 $contact = DBA::selectFirst('contact', ['url', 'hidden', 'network', 'protocol', 'gsid'], ['id' => $receiver, 'network' => Protocol::FEDERATED]);
604 if (!DBA::isResult($contact) || !self::isAPContact($contact, $networks)) {
608 if (!empty($profile = APContact::getByURL($contact['url'], false))) {
609 if ($contact['hidden'] || $always_bcc) {
610 $data['bcc'][] = $profile['url'];
612 $data['cc'][] = $profile['url'];
618 if (!empty($item['parent'])) {
619 $parents = Post::select(['id', 'author-link', 'owner-link', 'gravity', 'uri'], ['parent' => $item['parent']]);
620 while ($parent = Post::fetch($parents)) {
621 if ($parent['gravity'] == GRAVITY_PARENT) {
622 $profile = APContact::getByURL($parent['owner-link'], false);
623 if (!empty($profile)) {
624 if ($item['gravity'] != GRAVITY_PARENT) {
625 // Comments to forums are directed to the forum
626 // But comments to forums aren't directed to the followers collection
627 // This rule is only valid when the actor isn't the forum.
628 // The forum needs to transmit their content to their followers.
629 if (($profile['type'] == 'Group') && ($profile['url'] != ($actor_profile['url'] ?? ''))) {
630 $data['to'][] = $profile['url'];
632 $data['cc'][] = $profile['url'];
633 if (($item['private'] != Item::PRIVATE) && !empty($actor_profile['followers'])) {
634 $data['cc'][] = $actor_profile['followers'];
637 } elseif (!$exclusive) {
638 // Public thread parent post always are directed to the followers.
639 // This mustn't be done by posts that are directed to forum servers via the exclusive mention.
640 // But possibly in that case we could add the "followers" collection of the forum to the message.
641 if (($item['private'] != Item::PRIVATE) && !$forum_post) {
642 $data['cc'][] = $actor_profile['followers'];
648 // Don't include data from future posts
649 if ($parent['id'] >= $last_id) {
653 $profile = APContact::getByURL($parent['author-link'], false);
654 if (!empty($profile)) {
655 if (($profile['type'] == 'Group') || ($parent['uri'] == $item['thr-parent'])) {
656 $data['to'][] = $profile['url'];
658 $data['cc'][] = $profile['url'];
662 DBA::close($parents);
665 $data['to'] = array_unique($data['to']);
666 $data['cc'] = array_unique($data['cc']);
667 $data['bcc'] = array_unique($data['bcc']);
669 if (($key = array_search($item['author-link'], $data['to'])) !== false) {
670 unset($data['to'][$key]);
673 if (($key = array_search($item['author-link'], $data['cc'])) !== false) {
674 unset($data['cc'][$key]);
677 if (($key = array_search($item['author-link'], $data['bcc'])) !== false) {
678 unset($data['bcc'][$key]);
681 foreach ($data['to'] as $to) {
682 if (($key = array_search($to, $data['cc'])) !== false) {
683 unset($data['cc'][$key]);
686 if (($key = array_search($to, $data['bcc'])) !== false) {
687 unset($data['bcc'][$key]);
691 foreach ($data['cc'] as $cc) {
692 if (($key = array_search($cc, $data['bcc'])) !== false) {
693 unset($data['bcc'][$key]);
697 $receivers = ['to' => array_values($data['to']), 'cc' => array_values($data['cc']), 'bcc' => array_values($data['bcc'])];
700 unset($receivers['bcc']);
707 * Check if an inbox is archived
709 * @param string $url Inbox url
711 * @return boolean "true" if inbox is archived
713 public static function archivedInbox($url)
715 return DBA::exists('inbox-status', ['url' => $url, 'archive' => true]);
719 * Check if a given contact should be delivered via AP
721 * @param array $contact
722 * @param array $networks
726 private static function isAPContact(array $contact, array $networks)
728 if (in_array($contact['network'], $networks) || ($contact['protocol'] == Protocol::ACTIVITYPUB)) {
732 return GServer::getProtocol($contact['gsid'] ?? 0) == Post\DeliveryData::ACTIVITYPUB;
736 * Fetches a list of inboxes of followers of a given user
738 * @param integer $uid User ID
739 * @param boolean $personal fetch personal inboxes
740 * @param boolean $all_ap Retrieve all AP enabled inboxes
742 * @return array of follower inboxes
743 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
744 * @throws \ImagickException
746 public static function fetchTargetInboxesforUser($uid, $personal = false, bool $all_ap = false)
752 if (!empty($item['uid'])) {
753 $profile = User::getOwnerDataById($item['uid']);
754 if (!empty($profile)) {
755 $isforum = $profile['account-type'] == User::ACCOUNT_TYPE_COMMUNITY;
759 if (DI::config()->get('debug', 'total_ap_delivery') || $all_ap) {
760 // Will be activated in a later step
761 $networks = Protocol::FEDERATED;
763 // For now only send to these contacts:
764 $networks = [Protocol::ACTIVITYPUB, Protocol::OSTATUS];
767 $condition = ['uid' => $uid, 'archive' => false, 'pending' => false, 'blocked' => false, 'network' => Protocol::FEDERATED];
770 $condition['rel'] = [Contact::FOLLOWER, Contact::FRIEND];
773 $contacts = DBA::select('contact', ['id', 'url', 'network', 'protocol', 'gsid'], $condition);
774 while ($contact = DBA::fetch($contacts)) {
775 if (!self::isAPContact($contact, $networks)) {
779 if ($isforum && ($contact['network'] == Protocol::DFRN)) {
783 if (Network::isUrlBlocked($contact['url'])) {
787 $profile = APContact::getByURL($contact['url'], false);
788 if (!empty($profile)) {
789 if (empty($profile['sharedinbox']) || $personal || Contact::isLocal($contact['url'])) {
790 $target = $profile['inbox'];
792 $target = $profile['sharedinbox'];
794 if (!self::archivedInbox($target)) {
795 $inboxes[$target][] = $contact['id'];
799 DBA::close($contacts);
805 * Fetches an array of inboxes for the given item and user
807 * @param array $item Item array
808 * @param integer $uid User ID
809 * @param boolean $personal fetch personal inboxes
810 * @param integer $last_id Last item id for adding receivers
811 * @param boolean $forum_post "true" means that we are sending content to a forum
812 * @return array with inboxes
813 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
814 * @throws \ImagickException
816 public static function fetchTargetInboxes($item, $uid, $personal = false, $last_id = 0, $forum_post = false)
818 $permissions = self::createPermissionBlockForItem($item, true, $last_id, $forum_post);
819 if (empty($permissions)) {
825 if ($item['gravity'] == GRAVITY_ACTIVITY) {
826 $item_profile = APContact::getByURL($item['author-link'], false);
828 $item_profile = APContact::getByURL($item['owner-link'], false);
831 if (empty($item_profile)) {
835 $profile_uid = User::getIdForURL($item_profile['url']);
837 foreach (['to', 'cc', 'bto', 'bcc'] as $element) {
838 if (empty($permissions[$element])) {
842 $blindcopy = in_array($element, ['bto', 'bcc']);
844 foreach ($permissions[$element] as $receiver) {
845 if (empty($receiver) || Network::isUrlBlocked($receiver)) {
849 if ($item_profile && ($receiver == $item_profile['followers']) && ($uid == $profile_uid)) {
850 $inboxes = array_merge($inboxes, self::fetchTargetInboxesforUser($uid, $personal, self::isAPPost($last_id)));
852 $profile = APContact::getByURL($receiver, false);
853 if (!empty($profile)) {
854 $contact = Contact::getByURLForUser($receiver, $uid, false, ['id']);
856 if (empty($profile['sharedinbox']) || $personal || $blindcopy || Contact::isLocal($receiver)) {
857 $target = $profile['inbox'];
859 $target = $profile['sharedinbox'];
861 if (!self::archivedInbox($target)) {
862 $inboxes[$target][] = $contact['id'] ?? 0;
873 * Creates an array in the structure of the item table for a given mail id
875 * @param integer $mail_id
880 public static function ItemArrayFromMail($mail_id, $use_title = false)
882 $mail = DBA::selectFirst('mail', [], ['id' => $mail_id]);
883 if (!DBA::isResult($mail)) {
887 $reply = DBA::selectFirst('mail', ['uri', 'uri-id', 'from-url'], ['parent-uri' => $mail['parent-uri'], 'reply' => false]);
888 if (!DBA::isResult($reply)) {
892 // Making the post more compatible for Mastodon by:
893 // - Making it a note and not an article (no title)
894 // - Moving the title into the "summary" field that is used as a "content warning"
897 $mail['body'] = '[abstract]' . $mail['title'] . "[/abstract]\n" . $mail['body'];
901 $mail['author-link'] = $mail['owner-link'] = $mail['from-url'];
902 $mail['owner-id'] = $mail['author-id'];
903 $mail['allow_cid'] = '<'.$mail['contact-id'].'>';
904 $mail['allow_gid'] = '';
905 $mail['deny_cid'] = '';
906 $mail['deny_gid'] = '';
907 $mail['private'] = Item::PRIVATE;
908 $mail['deleted'] = false;
909 $mail['edited'] = $mail['created'];
910 $mail['plink'] = DI::baseUrl() . '/message/' . $mail['id'];
911 $mail['parent-uri'] = $reply['uri'];
912 $mail['parent-uri-id'] = $reply['uri-id'];
913 $mail['parent-author-id'] = Contact::getIdForURL($reply['from-url'], 0, false);
914 $mail['gravity'] = ($mail['reply'] ? GRAVITY_COMMENT: GRAVITY_PARENT);
915 $mail['event-type'] = '';
916 $mail['language'] = '';
923 * Creates an activity array for a given mail id
925 * @param integer $mail_id
926 * @param boolean $object_mode Is the activity item is used inside another object?
928 * @return array of activity
931 public static function createActivityFromMail($mail_id, $object_mode = false)
933 $mail = self::ItemArrayFromMail($mail_id);
937 $object = self::createNote($mail);
940 $data = ['@context' => ActivityPub::CONTEXT];
945 $data['id'] = $mail['uri'] . '/Create';
946 $data['type'] = 'Create';
947 $data['actor'] = $mail['author-link'];
948 $data['published'] = DateTimeFormat::utc($mail['created'] . '+00:00', DateTimeFormat::ATOM);
949 $data['instrument'] = self::getService();
950 $data = array_merge($data, self::createPermissionBlockForItem($mail, true));
952 if (empty($data['to']) && !empty($data['cc'])) {
953 $data['to'] = $data['cc'];
956 if (empty($data['to']) && !empty($data['bcc'])) {
957 $data['to'] = $data['bcc'];
963 $object['to'] = $data['to'];
964 $object['tag'] = [['type' => 'Mention', 'href' => $object['to'][0], 'name' => '']];
966 unset($object['cc']);
967 unset($object['bcc']);
969 $data['directMessage'] = true;
971 $data['object'] = $object;
973 $owner = User::getOwnerDataById($mail['uid']);
975 if (!$object_mode && !empty($owner)) {
976 return LDSignature::sign($data, $owner);
983 * Returns the activity type of a given item
987 * @return string with activity type
988 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
989 * @throws \ImagickException
991 private static function getTypeOfItem($item)
995 // Only check for a reshare, if it is a real reshare and no quoted reshare
996 if (strpos($item['body'], "[share") === 0) {
997 $announce = self::getAnnounceArray($item);
998 $reshared = !empty($announce);
1003 } elseif ($item['verb'] == Activity::POST) {
1004 if ($item['created'] == $item['edited']) {
1009 } elseif ($item['verb'] == Activity::LIKE) {
1011 } elseif ($item['verb'] == Activity::DISLIKE) {
1013 } elseif ($item['verb'] == Activity::ATTEND) {
1015 } elseif ($item['verb'] == Activity::ATTENDNO) {
1017 } elseif ($item['verb'] == Activity::ATTENDMAYBE) {
1018 $type = 'TentativeAccept';
1019 } elseif ($item['verb'] == Activity::FOLLOW) {
1021 } elseif ($item['verb'] == Activity::TAG) {
1023 } elseif ($item['verb'] == Activity::ANNOUNCE) {
1033 * Creates the activity or fetches it from the cache
1035 * @param integer $item_id
1036 * @param boolean $force Force new cache entry
1038 * @return array with the activity
1039 * @throws \Exception
1041 public static function createCachedActivityFromItem($item_id, $force = false)
1043 $cachekey = 'APDelivery:createActivity:' . $item_id;
1046 $data = DI::cache()->get($cachekey);
1047 if (!is_null($data)) {
1052 $data = self::createActivityFromItem($item_id);
1054 DI::cache()->set($cachekey, $data, Duration::QUARTER_HOUR);
1059 * Creates an activity array for a given item id
1061 * @param integer $item_id
1062 * @param boolean $object_mode Is the activity item is used inside another object?
1064 * @return false|array
1065 * @throws \Exception
1067 public static function createActivityFromItem(int $item_id, bool $object_mode = false)
1069 Logger::info('Fetching activity', ['item' => $item_id]);
1070 $item = Post::selectFirst(Item::DELIVER_FIELDLIST, ['id' => $item_id, 'parent-network' => Protocol::NATIVE_SUPPORT]);
1071 if (!DBA::isResult($item)) {
1075 // In case of a forum post ensure to return the original post if author and forum are on the same machine
1076 if (($item['gravity'] == GRAVITY_PARENT) && !empty($item['forum_mode'])) {
1077 $author = Contact::getById($item['author-id'], ['nurl']);
1078 if (!empty($author['nurl'])) {
1079 $self = Contact::selectFirst(['uid'], ['nurl' => $author['nurl'], 'self' => true]);
1080 if (!empty($self['uid'])) {
1081 $forum_item = Post::selectFirst(Item::DELIVER_FIELDLIST, ['uri-id' => $item['uri-id'], 'uid' => $self['uid']]);
1082 if (DBA::isResult($forum_item)) {
1083 $item = $forum_item;
1089 if (empty($item['uri-id'])) {
1090 Logger::warning('Item without uri-id', ['item' => $item]);
1094 if (!$item['deleted']) {
1095 $condition = ['item-uri' => $item['uri'], 'protocol' => Conversation::PARCEL_ACTIVITYPUB];
1096 $conversation = DBA::selectFirst('conversation', ['source'], $condition);
1097 if (!$item['origin'] && DBA::isResult($conversation)) {
1098 $data = json_decode($conversation['source'], true);
1099 if (!empty($data['type'])) {
1100 if (in_array($data['type'], ['Create', 'Update'])) {
1102 unset($data['@context']);
1103 unset($data['signature']);
1105 Logger::info('Return stored conversation', ['item' => $item_id]);
1107 } elseif (in_array('as:' . $data['type'], Receiver::CONTENT_TYPES)) {
1108 if (!empty($data['@context'])) {
1109 $context = $data['@context'];
1110 unset($data['@context']);
1112 unset($data['actor']);
1119 $type = self::getTypeOfItem($item);
1121 if (!$object_mode) {
1122 $data = ['@context' => $context ?? ActivityPub::CONTEXT];
1124 if ($item['deleted'] && ($item['gravity'] == GRAVITY_ACTIVITY)) {
1126 } elseif ($item['deleted']) {
1133 if ($type == 'Delete') {
1134 $data['id'] = Item::newURI($item['uid'], $item['guid']) . '/' . $type;;
1135 } elseif (($item['gravity'] == GRAVITY_ACTIVITY) && ($type != 'Undo')) {
1136 $data['id'] = $item['uri'];
1138 $data['id'] = $item['uri'] . '/' . $type;
1141 $data['type'] = $type;
1143 if (($type != 'Announce') || ($item['gravity'] != GRAVITY_PARENT)) {
1144 $data['actor'] = $item['author-link'];
1146 $data['actor'] = $item['owner-link'];
1149 $data['published'] = DateTimeFormat::utc($item['created'] . '+00:00', DateTimeFormat::ATOM);
1151 $data['instrument'] = self::getService();
1153 $data = array_merge($data, self::createPermissionBlockForItem($item, false));
1155 if (in_array($data['type'], ['Create', 'Update', 'Delete'])) {
1156 $data['object'] = $object ?? self::createNote($item);
1157 } elseif ($data['type'] == 'Add') {
1158 $data = self::createAddTag($item, $data);
1159 } elseif ($data['type'] == 'Announce') {
1160 if ($item['verb'] == ACTIVITY::ANNOUNCE) {
1161 $data['object'] = $item['thr-parent'];
1163 $data = self::createAnnounce($item, $data);
1165 } elseif ($data['type'] == 'Follow') {
1166 $data['object'] = $item['parent-uri'];
1167 } elseif ($data['type'] == 'Undo') {
1168 $data['object'] = self::createActivityFromItem($item_id, true);
1170 $data['diaspora:guid'] = $item['guid'];
1171 if (!empty($item['signed_text'])) {
1172 $data['diaspora:like'] = $item['signed_text'];
1174 $data['object'] = $item['thr-parent'];
1177 if (!empty($item['contact-uid'])) {
1178 $uid = $item['contact-uid'];
1180 $uid = $item['uid'];
1183 $owner = User::getOwnerDataById($uid);
1185 Logger::info('Fetched activity', ['item' => $item_id, 'uid' => $uid]);
1187 // We don't sign if we aren't the actor. This is important for relaying content especially for forums
1188 if (!$object_mode && !empty($owner) && ($data['actor'] == $owner['url'])) {
1189 return LDSignature::sign($data, $owner);
1194 /// @todo Create "conversation" entry
1198 * Creates a location entry for a given item array
1200 * @param array $item
1202 * @return array with location array
1204 private static function createLocation($item)
1206 $location = ['type' => 'Place'];
1208 if (!empty($item['location'])) {
1209 $location['name'] = $item['location'];
1214 if (empty($item['coord'])) {
1215 $coord = Map::getCoordinates($item['location']);
1217 $coords = explode(' ', $item['coord']);
1218 if (count($coords) == 2) {
1219 $coord = ['lat' => $coords[0], 'lon' => $coords[1]];
1223 if (!empty($coord['lat']) && !empty($coord['lon'])) {
1224 $location['latitude'] = $coord['lat'];
1225 $location['longitude'] = $coord['lon'];
1232 * Returns a tag array for a given item array
1234 * @param array $item
1236 * @return array of tags
1237 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1239 private static function createTagList($item)
1243 $terms = Tag::getByURIId($item['uri-id'], [Tag::HASHTAG, Tag::MENTION, Tag::IMPLICIT_MENTION, Tag::EXCLUSIVE_MENTION]);
1244 foreach ($terms as $term) {
1245 if ($term['type'] == Tag::HASHTAG) {
1246 $url = DI::baseUrl() . '/search?tag=' . urlencode($term['name']);
1247 $tags[] = ['type' => 'Hashtag', 'href' => $url, 'name' => '#' . $term['name']];
1249 $contact = Contact::getByURL($term['url'], false, ['addr']);
1250 if (empty($contact)) {
1253 if (!empty($contact['addr'])) {
1254 $mention = '@' . $contact['addr'];
1256 $mention = '@' . $term['url'];
1259 $tags[] = ['type' => 'Mention', 'href' => $term['url'], 'name' => $mention];
1263 $announce = self::getAnnounceArray($item);
1264 // Mention the original author upon commented reshares
1265 if (!empty($announce['comment'])) {
1266 $tags[] = ['type' => 'Mention', 'href' => $announce['actor']['url'], 'name' => '@' . $announce['actor']['addr']];
1273 * Adds attachment data to the JSON document
1275 * @param array $item Data of the item that is to be posted
1276 * @param string $type Object type
1278 * @return array with attachment data
1279 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1281 private static function createAttachmentList($item, $type)
1285 $uriids = [$item['uri-id']];
1286 $shared = BBCode::fetchShareAttributes($item['body']);
1287 if (!empty($shared['guid'])) {
1288 $shared_item = Post::selectFirst(['uri-id'], ['guid' => $shared['guid']]);
1289 if (!empty($shared_item['uri-id'])) {
1290 $uriids[] = $shared_item['uri-id'];
1295 foreach ($uriids as $uriid) {
1296 foreach (Post\Media::getByURIId($uriid, [Post\Media::AUDIO, Post\Media::IMAGE, Post\Media::VIDEO, Post\Media::DOCUMENT, Post\Media::TORRENT]) as $attachment) {
1297 if (in_array($attachment['url'], $urls)) {
1300 $urls[] = $attachment['url'];
1302 $attach = ['type' => 'Document',
1303 'mediaType' => $attachment['mimetype'],
1304 'url' => $attachment['url'],
1305 'name' => $attachment['description']];
1307 if (!empty($attachment['height'])) {
1308 $attach['height'] = $attachment['height'];
1311 if (!empty($attachment['width'])) {
1312 $attach['width'] = $attachment['width'];
1315 if (!empty($attachment['preview'])) {
1316 $attach['image'] = $attachment['preview'];
1319 $attachments[] = $attach;
1323 return $attachments;
1327 * Callback function to replace a Friendica style mention in a mention for a summary
1329 * @param array $match Matching values for the callback
1330 * @return string Replaced mention
1331 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1333 private static function mentionAddrCallback($match)
1335 if (empty($match[1])) {
1339 $data = Contact::getByURL($match[1], false, ['addr']);
1340 if (empty($data['addr'])) {
1344 return '@' . $data['addr'];
1348 * Remove image elements since they are added as attachment
1350 * @param string $body
1352 * @return string with removed images
1354 private static function removePictures($body)
1356 // Simplify image codes
1357 $body = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '[img]$3[/img]', $body);
1358 $body = preg_replace("/\[img\=(.*?)\](.*?)\[\/img\]/ism", '[img]$1[/img]', $body);
1360 // Now remove local links
1361 $body = preg_replace_callback(
1362 '/\[url=([^\[\]]*)\]\[img\](.*)\[\/img\]\[\/url\]/Usi',
1364 // We remove the link when it is a link to a local photo page
1365 if (Photo::isLocalPage($match[1])) {
1368 // otherwise we just return the link
1369 return '[url]' . $match[1] . '[/url]';
1374 // Remove all pictures
1375 $body = preg_replace("/\[img\]([^\[\]]*)\[\/img\]/Usi", '', $body);
1381 * Fetches the "context" value for a givem item array from the "conversation" table
1383 * @param array $item
1385 * @return string with context url
1386 * @throws \Exception
1388 private static function fetchContextURLForItem($item)
1390 $conversation = DBA::selectFirst('conversation', ['conversation-href', 'conversation-uri'], ['item-uri' => $item['parent-uri']]);
1391 if (DBA::isResult($conversation) && !empty($conversation['conversation-href'])) {
1392 $context_uri = $conversation['conversation-href'];
1393 } elseif (DBA::isResult($conversation) && !empty($conversation['conversation-uri'])) {
1394 $context_uri = $conversation['conversation-uri'];
1396 $context_uri = $item['parent-uri'] . '#context';
1398 return $context_uri;
1402 * Returns if the post contains sensitive content ("nsfw")
1404 * @param integer $uri_id
1407 * @throws \Exception
1409 private static function isSensitive($uri_id)
1411 return DBA::exists('tag-view', ['uri-id' => $uri_id, 'name' => 'nsfw']);
1415 * Creates event data
1417 * @param array $item
1419 * @return array with the event data
1420 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1422 private static function createEvent($item)
1425 $event['name'] = $item['event-summary'];
1426 $event['content'] = BBCode::convertForUriId($item['uri-id'], $item['event-desc'], BBCode::ACTIVITYPUB);
1427 $event['startTime'] = DateTimeFormat::utc($item['event-start'], 'c');
1429 if (!$item['event-nofinish']) {
1430 $event['endTime'] = DateTimeFormat::utc($item['event-finish'], 'c');
1433 if (!empty($item['event-location'])) {
1434 $item['location'] = $item['event-location'];
1435 $event['location'] = self::createLocation($item);
1438 // 2021.12: Backward compatibility value, all the events now "adjust" to the viewer timezone
1439 $event['dfrn:adjust'] = true;
1445 * Creates a note/article object array
1447 * @param array $item
1449 * @return array with the object data
1450 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1451 * @throws \ImagickException
1453 public static function createNote($item)
1459 if ($item['event-type'] == 'event') {
1461 } elseif (!empty($item['title'])) {
1467 if ($item['deleted']) {
1468 $type = 'Tombstone';
1472 $data['id'] = $item['uri'];
1473 $data['type'] = $type;
1475 if ($item['deleted']) {
1479 $data['summary'] = BBCode::toPlaintext(BBCode::getAbstract($item['body'], Protocol::ACTIVITYPUB));
1481 if ($item['uri'] != $item['thr-parent']) {
1482 $data['inReplyTo'] = $item['thr-parent'];
1484 $data['inReplyTo'] = null;
1487 $data['diaspora:guid'] = $item['guid'];
1488 $data['published'] = DateTimeFormat::utc($item['created'] . '+00:00', DateTimeFormat::ATOM);
1490 if ($item['created'] != $item['edited']) {
1491 $data['updated'] = DateTimeFormat::utc($item['edited'] . '+00:00', DateTimeFormat::ATOM);
1494 $data['url'] = $item['plink'];
1495 $data['attributedTo'] = $item['author-link'];
1496 $data['sensitive'] = self::isSensitive($item['uri-id']);
1497 $data['context'] = self::fetchContextURLForItem($item);
1499 if (!empty($item['title'])) {
1500 $data['name'] = BBCode::toPlaintext($item['title'], false);
1503 $permission_block = self::createPermissionBlockForItem($item, false);
1505 $body = $item['body'];
1507 if ($type == 'Note') {
1508 $body = $item['raw-body'] ?? self::removePictures($body);
1512 * @todo Improve the automated summary
1513 * This part is currently deactivated. The automated summary seems to be more
1514 * confusing than helping. But possibly we will find a better way.
1515 * So the code is left here for now as a reminder
1517 * } elseif (($type == 'Article') && empty($data['summary'])) {
1518 * $regexp = "/[@!]\[url\=([^\[\]]*)\].*?\[\/url\]/ism";
1519 * $summary = preg_replace_callback($regexp, ['self', 'mentionAddrCallback'], $body);
1520 * $data['summary'] = BBCode::toPlaintext(Plaintext::shorten(self::removePictures($summary), 1000));
1524 if (empty($item['uid']) || !Feature::isEnabled($item['uid'], 'explicit_mentions')) {
1525 $body = self::prependMentions($body, $item['uri-id'], $item['author-link']);
1528 if ($type == 'Event') {
1529 $data = array_merge($data, self::createEvent($item));
1531 $body = BBCode::setMentionsToNicknames($body);
1533 $data['content'] = BBCode::convertForUriId($item['uri-id'], $body, BBCode::ACTIVITYPUB);
1536 // The regular "content" field does contain a minimized HTML. This is done since systems like
1537 // Mastodon has got problems with - for example - embedded pictures.
1538 // The contentMap does contain the unmodified HTML.
1539 $language = self::getLanguage($item);
1540 if (!empty($language)) {
1541 $richbody = BBCode::setMentionsToNicknames($item['body'] ?? '');
1542 $richbody = BBCode::removeAttachment($richbody);
1544 $data['contentMap'][$language] = BBCode::convertForUriId($item['uri-id'], $richbody, BBCode::EXTERNAL);
1547 $data['source'] = ['content' => $item['body'], 'mediaType' => "text/bbcode"];
1549 if (!empty($item['signed_text']) && ($item['uri'] != $item['thr-parent'])) {
1550 $data['diaspora:comment'] = $item['signed_text'];
1553 $data['attachment'] = self::createAttachmentList($item, $type);
1554 $data['tag'] = self::createTagList($item);
1556 if (empty($data['location']) && (!empty($item['coord']) || !empty($item['location']))) {
1557 $data['location'] = self::createLocation($item);
1560 if (!empty($item['app'])) {
1561 $data['generator'] = ['type' => 'Application', 'name' => $item['app']];
1564 $data = array_merge($data, $permission_block);
1570 * Fetches the language from the post, the user or the system.
1572 * @param array $item
1574 * @return string language string
1576 private static function getLanguage(array $item)
1578 // Try to fetch the language from the post itself
1579 if (!empty($item['language'])) {
1580 $languages = array_keys(json_decode($item['language'], true));
1581 if (!empty($languages[0])) {
1582 return $languages[0];
1586 // Otherwise use the user's language
1587 if (!empty($item['uid'])) {
1588 $user = DBA::selectFirst('user', ['language'], ['uid' => $item['uid']]);
1589 if (!empty($user['language'])) {
1590 return $user['language'];
1594 // And finally just use the system language
1595 return DI::config()->get('system', 'language');
1599 * Creates an an "add tag" entry
1601 * @param array $item
1602 * @param array $data activity data
1604 * @return array with activity data for adding tags
1605 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1606 * @throws \ImagickException
1608 private static function createAddTag($item, $data)
1610 $object = XML::parseString($item['object']);
1611 $target = XML::parseString($item["target"]);
1613 $data['diaspora:guid'] = $item['guid'];
1614 $data['actor'] = $item['author-link'];
1615 $data['target'] = (string)$target->id;
1616 $data['summary'] = BBCode::toPlaintext($item['body']);
1617 $data['object'] = ['id' => (string)$object->id, 'type' => 'tag', 'name' => (string)$object->title, 'content' => (string)$object->content];
1623 * Creates an announce object entry
1625 * @param array $item
1626 * @param array $data activity data
1628 * @return array with activity data
1629 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1630 * @throws \ImagickException
1632 private static function createAnnounce($item, $data)
1634 $orig_body = $item['body'];
1635 $announce = self::getAnnounceArray($item);
1636 if (empty($announce)) {
1637 $data['type'] = 'Create';
1638 $data['object'] = self::createNote($item);
1642 if (empty($announce['comment'])) {
1643 // Pure announce, without a quote
1644 $data['type'] = 'Announce';
1645 $data['object'] = $announce['object']['uri'];
1650 $data['type'] = 'Create';
1651 $item['body'] = $announce['comment'] . "\n" . $announce['object']['plink'];
1652 $data['object'] = self::createNote($item);
1654 /// @todo Finally descide how to implement this in AP. This is a possible way:
1655 $data['object']['attachment'][] = self::createNote($announce['object']);
1657 $data['object']['source']['content'] = $orig_body;
1662 * Return announce related data if the item is an annunce
1664 * @param array $item
1668 public static function getAnnounceArray($item)
1670 $reshared = Item::getShareArray($item);
1671 if (empty($reshared['guid'])) {
1675 $reshared_item = Post::selectFirst(Item::DELIVER_FIELDLIST, ['guid' => $reshared['guid']]);
1676 if (!DBA::isResult($reshared_item)) {
1680 if (!in_array($reshared_item['network'], [Protocol::ACTIVITYPUB, Protocol::DFRN])) {
1684 $profile = APContact::getByURL($reshared_item['author-link'], false);
1685 if (empty($profile)) {
1689 return ['object' => $reshared_item, 'actor' => $profile, 'comment' => $reshared['comment']];
1693 * Checks if the provided item array is an announce
1695 * @param array $item
1699 public static function isAnnounce($item)
1701 if (!empty($item['verb']) && ($item['verb'] == Activity::ANNOUNCE)) {
1705 $announce = self::getAnnounceArray($item);
1706 if (empty($announce)) {
1710 return empty($announce['comment']);
1714 * Creates an activity id for a given contact id
1716 * @param integer $cid Contact ID of target
1718 * @return bool|string activity id
1720 public static function activityIDFromContact($cid)
1722 $contact = DBA::selectFirst('contact', ['uid', 'id', 'created'], ['id' => $cid]);
1723 if (!DBA::isResult($contact)) {
1727 $hash = hash('ripemd128', $contact['uid'].'-'.$contact['id'].'-'.$contact['created']);
1728 $uuid = substr($hash, 0, 8). '-' . substr($hash, 8, 4) . '-' . substr($hash, 12, 4) . '-' . substr($hash, 16, 4) . '-' . substr($hash, 20, 12);
1729 return DI::baseUrl() . '/activity/' . $uuid;
1733 * Transmits a contact suggestion to a given inbox
1735 * @param integer $uid User ID
1736 * @param string $inbox Target inbox
1737 * @param integer $suggestion_id Suggestion ID
1739 * @return boolean was the transmission successful?
1740 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1742 public static function sendContactSuggestion($uid, $inbox, $suggestion_id)
1744 $owner = User::getOwnerDataById($uid);
1746 $suggestion = DI::fsuggest()->selectOneById($suggestion_id);
1748 $data = ['@context' => ActivityPub::CONTEXT,
1749 'id' => DI::baseUrl() . '/activity/' . System::createGUID(),
1750 'type' => 'Announce',
1751 'actor' => $owner['url'],
1752 'object' => $suggestion->url,
1753 'content' => $suggestion->note,
1754 'instrument' => self::getService(),
1755 'to' => [ActivityPub::PUBLIC_COLLECTION],
1758 $signed = LDSignature::sign($data, $owner);
1760 Logger::info('Deliver profile deletion for user ' . $uid . ' to ' . $inbox . ' via ActivityPub');
1761 return HTTPSignature::transmit($signed, $inbox, $uid);
1765 * Transmits a profile relocation to a given inbox
1767 * @param integer $uid User ID
1768 * @param string $inbox Target inbox
1770 * @return boolean was the transmission successful?
1771 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1773 public static function sendProfileRelocation($uid, $inbox)
1775 $owner = User::getOwnerDataById($uid);
1777 $data = ['@context' => ActivityPub::CONTEXT,
1778 'id' => DI::baseUrl() . '/activity/' . System::createGUID(),
1779 'type' => 'dfrn:relocate',
1780 'actor' => $owner['url'],
1781 'object' => $owner['url'],
1782 'published' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
1783 'instrument' => self::getService(),
1784 'to' => [ActivityPub::PUBLIC_COLLECTION],
1787 $signed = LDSignature::sign($data, $owner);
1789 Logger::info('Deliver profile relocation for user ' . $uid . ' to ' . $inbox . ' via ActivityPub');
1790 return HTTPSignature::transmit($signed, $inbox, $uid);
1794 * Transmits a profile deletion to a given inbox
1796 * @param integer $uid User ID
1797 * @param string $inbox Target inbox
1799 * @return boolean was the transmission successful?
1800 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1802 public static function sendProfileDeletion($uid, $inbox)
1804 $owner = User::getOwnerDataById($uid);
1806 if (empty($owner)) {
1807 Logger::error('No owner data found, the deletion message cannot be processed.', ['user' => $uid]);
1811 if (empty($owner['uprvkey'])) {
1812 Logger::error('No private key for owner found, the deletion message cannot be processed.', ['user' => $uid]);
1816 $data = ['@context' => ActivityPub::CONTEXT,
1817 'id' => DI::baseUrl() . '/activity/' . System::createGUID(),
1819 'actor' => $owner['url'],
1820 'object' => $owner['url'],
1821 'published' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
1822 'instrument' => self::getService(),
1823 'to' => [ActivityPub::PUBLIC_COLLECTION],
1826 $signed = LDSignature::sign($data, $owner);
1828 Logger::info('Deliver profile deletion for user ' . $uid . ' to ' . $inbox . ' via ActivityPub');
1829 return HTTPSignature::transmit($signed, $inbox, $uid);
1833 * Transmits a profile change to a given inbox
1835 * @param integer $uid User ID
1836 * @param string $inbox Target inbox
1838 * @return boolean was the transmission successful?
1839 * @throws HTTPException\InternalServerErrorException
1840 * @throws HTTPException\NotFoundException
1841 * @throws \ImagickException
1843 public static function sendProfileUpdate(int $uid, string $inbox): bool
1845 $owner = User::getOwnerDataById($uid);
1846 $profile = APContact::getByURL($owner['url']);
1848 $data = ['@context' => ActivityPub::CONTEXT,
1849 'id' => DI::baseUrl() . '/activity/' . System::createGUID(),
1851 'actor' => $owner['url'],
1852 'object' => self::getProfile($uid),
1853 'published' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
1854 'instrument' => self::getService(),
1855 'to' => [$profile['followers']],
1858 $signed = LDSignature::sign($data, $owner);
1860 Logger::info('Deliver profile update for user ' . $uid . ' to ' . $inbox . ' via ActivityPub');
1861 return HTTPSignature::transmit($signed, $inbox, $uid);
1865 * Transmits a given activity to a target
1867 * @param string $activity Type name
1868 * @param string $target Target profile
1869 * @param integer $uid User ID
1871 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1872 * @throws \ImagickException
1873 * @throws \Exception
1875 public static function sendActivity($activity, $target, $uid, $id = '')
1877 $profile = APContact::getByURL($target);
1878 if (empty($profile['inbox'])) {
1879 Logger::warning('No inbox found for target', ['target' => $target, 'profile' => $profile]);
1883 $owner = User::getOwnerDataById($uid);
1886 $id = DI::baseUrl() . '/activity/' . System::createGUID();
1889 $data = ['@context' => ActivityPub::CONTEXT,
1891 'type' => $activity,
1892 'actor' => $owner['url'],
1893 'object' => $profile['url'],
1894 'instrument' => self::getService(),
1895 'to' => [$profile['url']]];
1897 Logger::info('Sending activity ' . $activity . ' to ' . $target . ' for user ' . $uid);
1899 $signed = LDSignature::sign($data, $owner);
1900 return HTTPSignature::transmit($signed, $profile['inbox'], $uid);
1904 * Transmits a "follow object" activity to a target
1905 * This is a preparation for sending automated "follow" requests when receiving "Announce" messages
1907 * @param string $object Object URL
1908 * @param string $target Target profile
1909 * @param integer $uid User ID
1911 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1912 * @throws \ImagickException
1913 * @throws \Exception
1915 public static function sendFollowObject($object, $target, $uid = 0)
1917 $profile = APContact::getByURL($target);
1918 if (empty($profile['inbox'])) {
1919 Logger::warning('No inbox found for target', ['target' => $target, 'profile' => $profile]);
1924 // Fetch the list of administrators
1925 $admin_mail = explode(',', str_replace(' ', '', DI::config()->get('config', 'admin_email')));
1927 // We need to use some user as a sender. It doesn't care who it will send. We will use an administrator account.
1928 $condition = ['verified' => true, 'blocked' => false, 'account_removed' => false, 'account_expired' => false, 'email' => $admin_mail];
1929 $first_user = DBA::selectFirst('user', ['uid'], $condition);
1930 $uid = $first_user['uid'];
1933 $condition = ['verb' => Activity::FOLLOW, 'uid' => 0, 'parent-uri' => $object,
1934 'author-id' => Contact::getPublicIdByUserId($uid)];
1935 if (Post::exists($condition)) {
1936 Logger::info('Follow for ' . $object . ' for user ' . $uid . ' does already exist.');
1940 $owner = User::getOwnerDataById($uid);
1942 $data = ['@context' => ActivityPub::CONTEXT,
1943 'id' => DI::baseUrl() . '/activity/' . System::createGUID(),
1945 'actor' => $owner['url'],
1946 'object' => $object,
1947 'instrument' => self::getService(),
1948 'to' => [$profile['url']]];
1950 Logger::info('Sending follow ' . $object . ' to ' . $target . ' for user ' . $uid);
1952 $signed = LDSignature::sign($data, $owner);
1953 return HTTPSignature::transmit($signed, $profile['inbox'], $uid);
1957 * Transmit a message that the contact request had been accepted
1959 * @param string $target Target profile
1961 * @param integer $uid User ID
1962 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1963 * @throws \ImagickException
1965 public static function sendContactAccept($target, $id, $uid)
1967 $profile = APContact::getByURL($target);
1968 if (empty($profile['inbox'])) {
1969 Logger::warning('No inbox found for target', ['target' => $target, 'profile' => $profile]);
1973 $owner = User::getOwnerDataById($uid);
1974 $data = ['@context' => ActivityPub::CONTEXT,
1975 'id' => DI::baseUrl() . '/activity/' . System::createGUID(),
1977 'actor' => $owner['url'],
1979 'id' => (string)$id,
1981 'actor' => $profile['url'],
1982 'object' => $owner['url']
1984 'instrument' => self::getService(),
1985 'to' => [$profile['url']]];
1987 Logger::debug('Sending accept to ' . $target . ' for user ' . $uid . ' with id ' . $id);
1989 $signed = LDSignature::sign($data, $owner);
1990 HTTPSignature::transmit($signed, $profile['inbox'], $uid);
1994 * Reject a contact request or terminates the contact relation
1996 * @param string $target Target profile
1998 * @param integer $uid User ID
1999 * @return bool Operation success
2000 * @throws HTTPException\InternalServerErrorException
2001 * @throws \ImagickException
2003 public static function sendContactReject($target, $id, $uid): bool
2005 $profile = APContact::getByURL($target);
2006 if (empty($profile['inbox'])) {
2007 Logger::warning('No inbox found for target', ['target' => $target, 'profile' => $profile]);
2011 $owner = User::getOwnerDataById($uid);
2012 $data = ['@context' => ActivityPub::CONTEXT,
2013 'id' => DI::baseUrl() . '/activity/' . System::createGUID(),
2015 'actor' => $owner['url'],
2017 'id' => (string)$id,
2019 'actor' => $profile['url'],
2020 'object' => $owner['url']
2022 'instrument' => self::getService(),
2023 'to' => [$profile['url']]];
2025 Logger::debug('Sending reject to ' . $target . ' for user ' . $uid . ' with id ' . $id);
2027 $signed = LDSignature::sign($data, $owner);
2028 return HTTPSignature::transmit($signed, $profile['inbox'], $uid);
2032 * Transmits a message that we don't want to follow this contact anymore
2034 * @param string $target Target profile
2035 * @param integer $uid User ID
2036 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2037 * @throws \ImagickException
2038 * @throws \Exception
2039 * @return bool success
2041 public static function sendContactUndo($target, $cid, $uid)
2043 $profile = APContact::getByURL($target);
2044 if (empty($profile['inbox'])) {
2045 Logger::warning('No inbox found for target', ['target' => $target, 'profile' => $profile]);
2049 $object_id = self::activityIDFromContact($cid);
2050 if (empty($object_id)) {
2054 $id = DI::baseUrl() . '/activity/' . System::createGUID();
2056 $owner = User::getOwnerDataById($uid);
2057 $data = ['@context' => ActivityPub::CONTEXT,
2060 'actor' => $owner['url'],
2061 'object' => ['id' => $object_id, 'type' => 'Follow',
2062 'actor' => $owner['url'],
2063 'object' => $profile['url']],
2064 'instrument' => self::getService(),
2065 'to' => [$profile['url']]];
2067 Logger::info('Sending undo to ' . $target . ' for user ' . $uid . ' with id ' . $id);
2069 $signed = LDSignature::sign($data, $owner);
2070 return HTTPSignature::transmit($signed, $profile['inbox'], $uid);
2073 private static function prependMentions($body, int $uriid, string $authorLink)
2077 foreach (Tag::getByURIId($uriid, [Tag::IMPLICIT_MENTION]) as $tag) {
2078 $profile = Contact::getByURL($tag['url'], false, ['addr', 'contact-type', 'nick']);
2079 if (!empty($profile['addr'])
2080 && $profile['contact-type'] != Contact::TYPE_COMMUNITY
2081 && !strstr($body, $profile['addr'])
2082 && !strstr($body, $tag['url'])
2083 && $tag['url'] !== $authorLink
2085 $mentions[] = '@[url=' . $tag['url'] . ']' . $profile['nick'] . '[/url]';
2089 $mentions[] = $body;
2091 return implode(' ', $mentions);