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)) {
440 $activity = json_decode($conversation['source'], true);
442 $actor = JsonLD::fetchElement($activity, 'actor', 'id');
443 if (!empty($actor)) {
444 $permissions['to'][] = $actor;
445 $profile = APContact::getByURL($actor);
450 $item_profile = APContact::getByURL($item['author-link']);
451 $exclude[] = $item['author-link'];
453 if ($item['gravity'] == GRAVITY_PARENT) {
454 $exclude[] = $item['owner-link'];
457 foreach (['to', 'cc', 'bto', 'bcc'] as $element) {
458 if (empty($activity[$element])) {
461 if (is_string($activity[$element])) {
462 $activity[$element] = [$activity[$element]];
465 foreach ($activity[$element] as $receiver) {
466 if (empty($receiver)) {
470 if (!empty($profile['followers']) && $receiver == $profile['followers'] && !empty($item_profile['followers'])) {
471 $permissions[$element][] = $item_profile['followers'];
472 } elseif (!in_array($receiver, $exclude)) {
473 $permissions[$element][] = $receiver;
481 * Check if the given item id is from ActivityPub
483 * @param integer $item_id
484 * @return boolean "true" if the post is from ActivityPub
486 private static function isAPPost(int $item_id)
488 if (empty($item_id)) {
492 return Post::exists(['id' => $item_id, 'network' => Protocol::ACTIVITYPUB]);
496 * Creates an array of permissions from an item thread
498 * @param array $item Item array
499 * @param boolean $blindcopy addressing via "bcc" or "cc"?
500 * @param integer $last_id Last item id for adding receivers
501 * @param boolean $forum_mode "true" means that we are sending content to a forum
503 * @return array with permission data
504 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
505 * @throws \ImagickException
507 private static function createPermissionBlockForItem($item, $blindcopy, $last_id = 0, $forum_mode = false)
510 $last_id = $item['id'];
515 // Check if we should always deliver our stuff via BCC
516 if (!empty($item['uid'])) {
517 $profile = User::getOwnerDataById($item['uid']);
518 if (!empty($profile)) {
519 $always_bcc = $profile['hide-friends'];
523 if (DI::config()->get('system', 'ap_always_bcc')) {
527 if (self::isAnnounce($item) || DI::config()->get('debug', 'total_ap_delivery') || self::isAPPost($last_id)) {
528 // Will be activated in a later step
529 $networks = Protocol::FEDERATED;
531 // For now only send to these contacts:
532 $networks = [Protocol::ACTIVITYPUB, Protocol::OSTATUS];
535 $data = ['to' => [], 'cc' => [], 'bcc' => []];
537 if ($item['gravity'] == GRAVITY_PARENT) {
538 $actor_profile = APContact::getByURL($item['owner-link']);
540 $actor_profile = APContact::getByURL($item['author-link']);
545 $terms = Tag::getByURIId($item['uri-id'], [Tag::MENTION, Tag::IMPLICIT_MENTION, Tag::EXCLUSIVE_MENTION]);
547 if ($item['private'] != Item::PRIVATE) {
548 // Directly mention the original author upon a quoted reshare.
549 // Else just ensure that the original author receives the reshare.
550 $announce = self::getAnnounceArray($item);
551 if (!empty($announce['comment'])) {
552 $data['to'][] = $announce['actor']['url'];
553 } elseif (!empty($announce)) {
554 $data['cc'][] = $announce['actor']['url'];
557 $data = array_merge($data, self::fetchPermissionBlockFromConversation($item));
559 // Check if the item is completely public or unlisted
560 if ($item['private'] == Item::PUBLIC) {
561 $data['to'][] = ActivityPub::PUBLIC_COLLECTION;
563 $data['cc'][] = ActivityPub::PUBLIC_COLLECTION;
566 foreach ($terms as $term) {
567 $profile = APContact::getByURL($term['url'], false);
568 if (!empty($profile)) {
569 if ($term['type'] == Tag::EXCLUSIVE_MENTION) {
571 if (!empty($profile['followers']) && ($profile['type'] == 'Group')) {
572 $data['cc'][] = $profile['followers'];
575 $data['to'][] = $profile['url'];
579 $receiver_list = Item::enumeratePermissions($item, true);
581 foreach ($terms as $term) {
582 $cid = Contact::getIdForURL($term['url'], $item['uid']);
583 if (!empty($cid) && in_array($cid, $receiver_list)) {
584 $contact = DBA::selectFirst('contact', ['url', 'network', 'protocol', 'gsid'], ['id' => $cid, 'network' => Protocol::FEDERATED]);
585 if (!DBA::isResult($contact) || !self::isAPContact($contact, $networks)) {
589 if (!empty($profile = APContact::getByURL($contact['url'], false))) {
590 $data['to'][] = $profile['url'];
595 foreach ($receiver_list as $receiver) {
596 $contact = DBA::selectFirst('contact', ['url', 'hidden', 'network', 'protocol', 'gsid'], ['id' => $receiver, 'network' => Protocol::FEDERATED]);
597 if (!DBA::isResult($contact) || !self::isAPContact($contact, $networks)) {
601 if (!empty($profile = APContact::getByURL($contact['url'], false))) {
602 if ($contact['hidden'] || $always_bcc) {
603 $data['bcc'][] = $profile['url'];
605 $data['cc'][] = $profile['url'];
611 if (!empty($item['parent'])) {
612 $parents = Post::select(['id', 'author-link', 'owner-link', 'gravity', 'uri'], ['parent' => $item['parent']]);
613 while ($parent = Post::fetch($parents)) {
614 if ($parent['gravity'] == GRAVITY_PARENT) {
615 $profile = APContact::getByURL($parent['owner-link'], false);
616 if (!empty($profile)) {
617 if ($item['gravity'] != GRAVITY_PARENT) {
618 // Comments to forums are directed to the forum
619 // But comments to forums aren't directed to the followers collection
620 // This rule is only valid when the actor isn't the forum.
621 // The forum needs to transmit their content to their followers.
622 if (($profile['type'] == 'Group') && ($profile['url'] != ($actor_profile['url'] ?? ''))) {
623 $data['to'][] = $profile['url'];
625 $data['cc'][] = $profile['url'];
626 if (($item['private'] != Item::PRIVATE) && !empty($actor_profile['followers'])) {
627 $data['cc'][] = $actor_profile['followers'];
630 } elseif (!$exclusive) {
631 // Public thread parent post always are directed to the followers.
632 // This mustn't be done by posts that are directed to forum servers via the exclusive mention.
633 // But possibly in that case we could add the "followers" collection of the forum to the message.
634 if (($item['private'] != Item::PRIVATE) && !$forum_mode) {
635 $data['cc'][] = $actor_profile['followers'];
641 // Don't include data from future posts
642 if ($parent['id'] >= $last_id) {
646 $profile = APContact::getByURL($parent['author-link'], false);
647 if (!empty($profile)) {
648 if (($profile['type'] == 'Group') || ($parent['uri'] == $item['thr-parent'])) {
649 $data['to'][] = $profile['url'];
651 $data['cc'][] = $profile['url'];
655 DBA::close($parents);
658 $data['to'] = array_unique($data['to']);
659 $data['cc'] = array_unique($data['cc']);
660 $data['bcc'] = array_unique($data['bcc']);
662 if (($key = array_search($item['author-link'], $data['to'])) !== false) {
663 unset($data['to'][$key]);
666 if (($key = array_search($item['author-link'], $data['cc'])) !== false) {
667 unset($data['cc'][$key]);
670 if (($key = array_search($item['author-link'], $data['bcc'])) !== false) {
671 unset($data['bcc'][$key]);
674 foreach ($data['to'] as $to) {
675 if (($key = array_search($to, $data['cc'])) !== false) {
676 unset($data['cc'][$key]);
679 if (($key = array_search($to, $data['bcc'])) !== false) {
680 unset($data['bcc'][$key]);
684 foreach ($data['cc'] as $cc) {
685 if (($key = array_search($cc, $data['bcc'])) !== false) {
686 unset($data['bcc'][$key]);
690 $receivers = ['to' => array_values($data['to']), 'cc' => array_values($data['cc']), 'bcc' => array_values($data['bcc'])];
693 unset($receivers['bcc']);
700 * Check if an inbox is archived
702 * @param string $url Inbox url
704 * @return boolean "true" if inbox is archived
706 public static function archivedInbox($url)
708 return DBA::exists('inbox-status', ['url' => $url, 'archive' => true]);
712 * Check if a given contact should be delivered via AP
714 * @param array $contact
715 * @param array $networks
719 private static function isAPContact(array $contact, array $networks)
721 if (in_array($contact['network'], $networks) || ($contact['protocol'] == Protocol::ACTIVITYPUB)) {
725 return GServer::getProtocol($contact['gsid'] ?? 0) == Post\DeliveryData::ACTIVITYPUB;
729 * Fetches a list of inboxes of followers of a given user
731 * @param integer $uid User ID
732 * @param boolean $personal fetch personal inboxes
733 * @param boolean $all_ap Retrieve all AP enabled inboxes
735 * @return array of follower inboxes
736 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
737 * @throws \ImagickException
739 public static function fetchTargetInboxesforUser($uid, $personal = false, bool $all_ap = false)
745 if (!empty($item['uid'])) {
746 $profile = User::getOwnerDataById($item['uid']);
747 if (!empty($profile)) {
748 $isforum = $profile['account-type'] == User::ACCOUNT_TYPE_COMMUNITY;
752 if (DI::config()->get('debug', 'total_ap_delivery') || $all_ap) {
753 // Will be activated in a later step
754 $networks = Protocol::FEDERATED;
756 // For now only send to these contacts:
757 $networks = [Protocol::ACTIVITYPUB, Protocol::OSTATUS];
760 $condition = ['uid' => $uid, 'archive' => false, 'pending' => false, 'blocked' => false, 'network' => Protocol::FEDERATED];
763 $condition['rel'] = [Contact::FOLLOWER, Contact::FRIEND];
766 $contacts = DBA::select('contact', ['id', 'url', 'network', 'protocol', 'gsid'], $condition);
767 while ($contact = DBA::fetch($contacts)) {
768 if (!self::isAPContact($contact, $networks)) {
772 if ($isforum && ($contact['network'] == Protocol::DFRN)) {
776 if (Network::isUrlBlocked($contact['url'])) {
780 $profile = APContact::getByURL($contact['url'], false);
781 if (!empty($profile)) {
782 if (empty($profile['sharedinbox']) || $personal || Contact::isLocal($contact['url'])) {
783 $target = $profile['inbox'];
785 $target = $profile['sharedinbox'];
787 if (!self::archivedInbox($target)) {
788 $inboxes[$target][] = $contact['id'];
792 DBA::close($contacts);
798 * Fetches an array of inboxes for the given item and user
800 * @param array $item Item array
801 * @param integer $uid User ID
802 * @param boolean $personal fetch personal inboxes
803 * @param integer $last_id Last item id for adding receivers
804 * @param boolean $forum_mode "true" means that we are sending content to a forum
805 * @return array with inboxes
806 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
807 * @throws \ImagickException
809 public static function fetchTargetInboxes($item, $uid, $personal = false, $last_id = 0, $forum_mode = false)
811 $permissions = self::createPermissionBlockForItem($item, true, $last_id, $forum_mode);
812 if (empty($permissions)) {
818 if ($item['gravity'] == GRAVITY_ACTIVITY) {
819 $item_profile = APContact::getByURL($item['author-link'], false);
821 $item_profile = APContact::getByURL($item['owner-link'], false);
824 if (empty($item_profile)) {
828 $profile_uid = User::getIdForURL($item_profile['url']);
830 foreach (['to', 'cc', 'bto', 'bcc'] as $element) {
831 if (empty($permissions[$element])) {
835 $blindcopy = in_array($element, ['bto', 'bcc']);
837 foreach ($permissions[$element] as $receiver) {
838 if (empty($receiver) || Network::isUrlBlocked($receiver)) {
842 if ($item_profile && ($receiver == $item_profile['followers']) && ($uid == $profile_uid)) {
843 $inboxes = array_merge($inboxes, self::fetchTargetInboxesforUser($uid, $personal, self::isAPPost($last_id)));
845 $profile = APContact::getByURL($receiver, false);
846 if (!empty($profile)) {
847 $contact = Contact::getByURLForUser($receiver, $uid, false, ['id']);
849 if (empty($profile['sharedinbox']) || $personal || $blindcopy || Contact::isLocal($receiver)) {
850 $target = $profile['inbox'];
852 $target = $profile['sharedinbox'];
854 if (!self::archivedInbox($target)) {
855 $inboxes[$target][] = $contact['id'] ?? 0;
866 * Creates an array in the structure of the item table for a given mail id
868 * @param integer $mail_id
873 public static function ItemArrayFromMail($mail_id, $use_title = false)
875 $mail = DBA::selectFirst('mail', [], ['id' => $mail_id]);
876 if (!DBA::isResult($mail)) {
880 $reply = DBA::selectFirst('mail', ['uri', 'uri-id', 'from-url'], ['parent-uri' => $mail['parent-uri'], 'reply' => false]);
881 if (!DBA::isResult($reply)) {
885 // Making the post more compatible for Mastodon by:
886 // - Making it a note and not an article (no title)
887 // - Moving the title into the "summary" field that is used as a "content warning"
890 $mail['body'] = '[abstract]' . $mail['title'] . "[/abstract]\n" . $mail['body'];
894 $mail['author-link'] = $mail['owner-link'] = $mail['from-url'];
895 $mail['owner-id'] = $mail['author-id'];
896 $mail['allow_cid'] = '<'.$mail['contact-id'].'>';
897 $mail['allow_gid'] = '';
898 $mail['deny_cid'] = '';
899 $mail['deny_gid'] = '';
900 $mail['private'] = Item::PRIVATE;
901 $mail['deleted'] = false;
902 $mail['edited'] = $mail['created'];
903 $mail['plink'] = DI::baseUrl() . '/message/' . $mail['id'];
904 $mail['parent-uri'] = $reply['uri'];
905 $mail['parent-uri-id'] = $reply['uri-id'];
906 $mail['parent-author-id'] = Contact::getIdForURL($reply['from-url'], 0, false);
907 $mail['gravity'] = ($mail['reply'] ? GRAVITY_COMMENT: GRAVITY_PARENT);
908 $mail['event-type'] = '';
909 $mail['language'] = '';
916 * Creates an activity array for a given mail id
918 * @param integer $mail_id
919 * @param boolean $object_mode Is the activity item is used inside another object?
921 * @return array of activity
924 public static function createActivityFromMail($mail_id, $object_mode = false)
926 $mail = self::ItemArrayFromMail($mail_id);
930 $object = self::createNote($mail);
933 $data = ['@context' => ActivityPub::CONTEXT];
938 $data['id'] = $mail['uri'] . '/Create';
939 $data['type'] = 'Create';
940 $data['actor'] = $mail['author-link'];
941 $data['published'] = DateTimeFormat::utc($mail['created'] . '+00:00', DateTimeFormat::ATOM);
942 $data['instrument'] = self::getService();
943 $data = array_merge($data, self::createPermissionBlockForItem($mail, true));
945 if (empty($data['to']) && !empty($data['cc'])) {
946 $data['to'] = $data['cc'];
949 if (empty($data['to']) && !empty($data['bcc'])) {
950 $data['to'] = $data['bcc'];
956 $object['to'] = $data['to'];
957 $object['tag'] = [['type' => 'Mention', 'href' => $object['to'][0], 'name' => '']];
959 unset($object['cc']);
960 unset($object['bcc']);
962 $data['directMessage'] = true;
964 $data['object'] = $object;
966 $owner = User::getOwnerDataById($mail['uid']);
968 if (!$object_mode && !empty($owner)) {
969 return LDSignature::sign($data, $owner);
976 * Returns the activity type of a given item
980 * @return string with activity type
981 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
982 * @throws \ImagickException
984 private static function getTypeOfItem($item)
988 // Only check for a reshare, if it is a real reshare and no quoted reshare
989 if (strpos($item['body'], "[share") === 0) {
990 $announce = self::getAnnounceArray($item);
991 $reshared = !empty($announce);
996 } elseif ($item['verb'] == Activity::POST) {
997 if ($item['created'] == $item['edited']) {
1002 } elseif ($item['verb'] == Activity::LIKE) {
1004 } elseif ($item['verb'] == Activity::DISLIKE) {
1006 } elseif ($item['verb'] == Activity::ATTEND) {
1008 } elseif ($item['verb'] == Activity::ATTENDNO) {
1010 } elseif ($item['verb'] == Activity::ATTENDMAYBE) {
1011 $type = 'TentativeAccept';
1012 } elseif ($item['verb'] == Activity::FOLLOW) {
1014 } elseif ($item['verb'] == Activity::TAG) {
1016 } elseif ($item['verb'] == Activity::ANNOUNCE) {
1026 * Creates the activity or fetches it from the cache
1028 * @param integer $item_id
1029 * @param boolean $force Force new cache entry
1031 * @return array with the activity
1032 * @throws \Exception
1034 public static function createCachedActivityFromItem($item_id, $force = false)
1036 $cachekey = 'APDelivery:createActivity:' . $item_id;
1039 $data = DI::cache()->get($cachekey);
1040 if (!is_null($data)) {
1045 $data = self::createActivityFromItem($item_id);
1047 DI::cache()->set($cachekey, $data, Duration::QUARTER_HOUR);
1052 * Creates an activity array for a given item id
1054 * @param integer $item_id
1055 * @param boolean $object_mode Is the activity item is used inside another object?
1057 * @return false|array
1058 * @throws \Exception
1060 public static function createActivityFromItem(int $item_id, bool $object_mode = false)
1062 Logger::info('Fetching activity', ['item' => $item_id]);
1063 $item = Post::selectFirst(Item::DELIVER_FIELDLIST, ['id' => $item_id, 'parent-network' => Protocol::NATIVE_SUPPORT]);
1064 if (!DBA::isResult($item)) {
1068 // In case of a forum post ensure to return the original post if author and forum are on the same machine
1069 if (($item['gravity'] == GRAVITY_PARENT) && !empty($item['forum_mode'])) {
1070 $author = Contact::getById($item['author-id'], ['nurl']);
1071 if (!empty($author['nurl'])) {
1072 $self = Contact::selectFirst(['uid'], ['nurl' => $author['nurl'], 'self' => true]);
1073 if (!empty($self['uid'])) {
1074 $forum_item = Post::selectFirst(Item::DELIVER_FIELDLIST, ['uri-id' => $item['uri-id'], 'uid' => $self['uid']]);
1075 if (DBA::isResult($forum_item)) {
1076 $item = $forum_item;
1082 if (empty($item['uri-id'])) {
1083 Logger::warning('Item without uri-id', ['item' => $item]);
1087 if (!$item['deleted']) {
1088 $condition = ['item-uri' => $item['uri'], 'protocol' => Conversation::PARCEL_ACTIVITYPUB];
1089 $conversation = DBA::selectFirst('conversation', ['source'], $condition);
1090 if (!$item['origin'] && DBA::isResult($conversation)) {
1091 $data = json_decode($conversation['source'], true);
1092 if (!empty($data['type'])) {
1093 if (in_array($data['type'], ['Create', 'Update'])) {
1095 unset($data['@context']);
1096 unset($data['signature']);
1098 Logger::info('Return stored conversation', ['item' => $item_id]);
1100 } elseif (in_array('as:' . $data['type'], Receiver::CONTENT_TYPES)) {
1101 if (!empty($data['@context'])) {
1102 $context = $data['@context'];
1103 unset($data['@context']);
1105 unset($data['actor']);
1112 $type = self::getTypeOfItem($item);
1114 if (!$object_mode) {
1115 $data = ['@context' => $context ?? ActivityPub::CONTEXT];
1117 if ($item['deleted'] && ($item['gravity'] == GRAVITY_ACTIVITY)) {
1119 } elseif ($item['deleted']) {
1126 if ($type == 'Delete') {
1127 $data['id'] = Item::newURI($item['uid'], $item['guid']) . '/' . $type;;
1128 } elseif (($item['gravity'] == GRAVITY_ACTIVITY) && ($type != 'Undo')) {
1129 $data['id'] = $item['uri'];
1131 $data['id'] = $item['uri'] . '/' . $type;
1134 $data['type'] = $type;
1136 if (($type != 'Announce') || ($item['gravity'] != GRAVITY_PARENT)) {
1137 $data['actor'] = $item['author-link'];
1139 $data['actor'] = $item['owner-link'];
1142 $data['published'] = DateTimeFormat::utc($item['created'] . '+00:00', DateTimeFormat::ATOM);
1144 $data['instrument'] = self::getService();
1146 $data = array_merge($data, self::createPermissionBlockForItem($item, false));
1148 if (in_array($data['type'], ['Create', 'Update', 'Delete'])) {
1149 $data['object'] = $object ?? self::createNote($item);
1150 } elseif ($data['type'] == 'Add') {
1151 $data = self::createAddTag($item, $data);
1152 } elseif ($data['type'] == 'Announce') {
1153 if ($item['verb'] == ACTIVITY::ANNOUNCE) {
1154 $data['object'] = $item['thr-parent'];
1156 $data = self::createAnnounce($item, $data);
1158 } elseif ($data['type'] == 'Follow') {
1159 $data['object'] = $item['parent-uri'];
1160 } elseif ($data['type'] == 'Undo') {
1161 $data['object'] = self::createActivityFromItem($item_id, true);
1163 $data['diaspora:guid'] = $item['guid'];
1164 if (!empty($item['signed_text'])) {
1165 $data['diaspora:like'] = $item['signed_text'];
1167 $data['object'] = $item['thr-parent'];
1170 if (!empty($item['contact-uid'])) {
1171 $uid = $item['contact-uid'];
1173 $uid = $item['uid'];
1176 $owner = User::getOwnerDataById($uid);
1178 Logger::info('Fetched activity', ['item' => $item_id, 'uid' => $uid]);
1180 // We don't sign if we aren't the actor. This is important for relaying content especially for forums
1181 if (!$object_mode && !empty($owner) && ($data['actor'] == $owner['url'])) {
1182 return LDSignature::sign($data, $owner);
1187 /// @todo Create "conversation" entry
1191 * Creates a location entry for a given item array
1193 * @param array $item
1195 * @return array with location array
1197 private static function createLocation($item)
1199 $location = ['type' => 'Place'];
1201 if (!empty($item['location'])) {
1202 $location['name'] = $item['location'];
1207 if (empty($item['coord'])) {
1208 $coord = Map::getCoordinates($item['location']);
1210 $coords = explode(' ', $item['coord']);
1211 if (count($coords) == 2) {
1212 $coord = ['lat' => $coords[0], 'lon' => $coords[1]];
1216 if (!empty($coord['lat']) && !empty($coord['lon'])) {
1217 $location['latitude'] = $coord['lat'];
1218 $location['longitude'] = $coord['lon'];
1225 * Returns a tag array for a given item array
1227 * @param array $item
1229 * @return array of tags
1230 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1232 private static function createTagList($item)
1236 $terms = Tag::getByURIId($item['uri-id'], [Tag::HASHTAG, Tag::MENTION, Tag::IMPLICIT_MENTION, Tag::EXCLUSIVE_MENTION]);
1237 foreach ($terms as $term) {
1238 if ($term['type'] == Tag::HASHTAG) {
1239 $url = DI::baseUrl() . '/search?tag=' . urlencode($term['name']);
1240 $tags[] = ['type' => 'Hashtag', 'href' => $url, 'name' => '#' . $term['name']];
1242 $contact = Contact::getByURL($term['url'], false, ['addr']);
1243 if (empty($contact)) {
1246 if (!empty($contact['addr'])) {
1247 $mention = '@' . $contact['addr'];
1249 $mention = '@' . $term['url'];
1252 $tags[] = ['type' => 'Mention', 'href' => $term['url'], 'name' => $mention];
1256 $announce = self::getAnnounceArray($item);
1257 // Mention the original author upon commented reshares
1258 if (!empty($announce['comment'])) {
1259 $tags[] = ['type' => 'Mention', 'href' => $announce['actor']['url'], 'name' => '@' . $announce['actor']['addr']];
1266 * Adds attachment data to the JSON document
1268 * @param array $item Data of the item that is to be posted
1269 * @param string $type Object type
1271 * @return array with attachment data
1272 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1274 private static function createAttachmentList($item, $type)
1278 $uriids = [$item['uri-id']];
1279 $shared = BBCode::fetchShareAttributes($item['body']);
1280 if (!empty($shared['guid'])) {
1281 $shared_item = Post::selectFirst(['uri-id'], ['guid' => $shared['guid']]);
1282 if (!empty($shared_item['uri-id'])) {
1283 $uriids[] = $shared_item['uri-id'];
1288 foreach ($uriids as $uriid) {
1289 foreach (Post\Media::getByURIId($uriid, [Post\Media::DOCUMENT, Post\Media::TORRENT]) as $attachment) {
1290 if (in_array($attachment['url'], $urls)) {
1293 $urls[] = $attachment['url'];
1295 $attach = ['type' => 'Document',
1296 'mediaType' => $attachment['mimetype'],
1297 'url' => $attachment['url'],
1298 'name' => $attachment['description']];
1300 if (!empty($attachment['height'])) {
1301 $attach['height'] = $attachment['height'];
1304 if (!empty($attachment['width'])) {
1305 $attach['width'] = $attachment['width'];
1308 if (!empty($attachment['preview'])) {
1309 $attach['image'] = $attachment['preview'];
1312 $attachments[] = $attach;
1316 if ($type != 'Note') {
1317 return $attachments;
1320 foreach ($uriids as $uriid) {
1321 foreach (Post\Media::getByURIId($uriid, [Post\Media::AUDIO, Post\Media::IMAGE, Post\Media::VIDEO]) as $attachment) {
1322 if (in_array($attachment['url'], $urls)) {
1325 $urls[] = $attachment['url'];
1327 $attach = ['type' => 'Document',
1328 'mediaType' => $attachment['mimetype'],
1329 'url' => $attachment['url'],
1330 'name' => $attachment['description']];
1332 if (!empty($attachment['height'])) {
1333 $attach['height'] = $attachment['height'];
1336 if (!empty($attachment['width'])) {
1337 $attach['width'] = $attachment['width'];
1340 if (!empty($attachment['preview'])) {
1341 $attach['image'] = $attachment['preview'];
1344 $attachments[] = $attach;
1346 // Currently deactivated, since it creates side effects on Mastodon and Pleroma.
1347 // It will be activated, once this cleared.
1349 foreach (Post\Media::getByURIId($uriid, [Post\Media::HTML]) as $attachment) {
1350 if (in_array($attachment['url'], $urls)) {
1353 $urls[] = $attachment['url'];
1355 $attachments[] = ['type' => 'Page',
1356 'mediaType' => $attachment['mimetype'],
1357 'url' => $attachment['url'],
1358 'name' => $attachment['description']];
1362 return $attachments;
1366 * Callback function to replace a Friendica style mention in a mention for a summary
1368 * @param array $match Matching values for the callback
1369 * @return string Replaced mention
1370 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1372 private static function mentionAddrCallback($match)
1374 if (empty($match[1])) {
1378 $data = Contact::getByURL($match[1], false, ['addr']);
1379 if (empty($data['addr'])) {
1383 return '@' . $data['addr'];
1387 * Remove image elements since they are added as attachment
1389 * @param string $body
1391 * @return string with removed images
1393 private static function removePictures($body)
1395 // Simplify image codes
1396 $body = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '[img]$3[/img]', $body);
1397 $body = preg_replace("/\[img\=(.*?)\](.*?)\[\/img\]/ism", '[img]$1[/img]', $body);
1399 // Now remove local links
1400 $body = preg_replace_callback(
1401 '/\[url=([^\[\]]*)\]\[img\](.*)\[\/img\]\[\/url\]/Usi',
1403 // We remove the link when it is a link to a local photo page
1404 if (Photo::isLocalPage($match[1])) {
1407 // otherwise we just return the link
1408 return '[url]' . $match[1] . '[/url]';
1413 // Remove all pictures
1414 $body = preg_replace("/\[img\]([^\[\]]*)\[\/img\]/Usi", '', $body);
1420 * Fetches the "context" value for a givem item array from the "conversation" table
1422 * @param array $item
1424 * @return string with context url
1425 * @throws \Exception
1427 private static function fetchContextURLForItem($item)
1429 $conversation = DBA::selectFirst('conversation', ['conversation-href', 'conversation-uri'], ['item-uri' => $item['parent-uri']]);
1430 if (DBA::isResult($conversation) && !empty($conversation['conversation-href'])) {
1431 $context_uri = $conversation['conversation-href'];
1432 } elseif (DBA::isResult($conversation) && !empty($conversation['conversation-uri'])) {
1433 $context_uri = $conversation['conversation-uri'];
1435 $context_uri = $item['parent-uri'] . '#context';
1437 return $context_uri;
1441 * Returns if the post contains sensitive content ("nsfw")
1443 * @param integer $uri_id
1446 * @throws \Exception
1448 private static function isSensitive($uri_id)
1450 return DBA::exists('tag-view', ['uri-id' => $uri_id, 'name' => 'nsfw']);
1454 * Creates event data
1456 * @param array $item
1458 * @return array with the event data
1459 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1461 private static function createEvent($item)
1464 $event['name'] = $item['event-summary'];
1465 $event['content'] = BBCode::convertForUriId($item['uri-id'], $item['event-desc'], BBCode::ACTIVITYPUB);
1466 $event['startTime'] = DateTimeFormat::utc($item['event-start'], 'c');
1468 if (!$item['event-nofinish']) {
1469 $event['endTime'] = DateTimeFormat::utc($item['event-finish'], 'c');
1472 if (!empty($item['event-location'])) {
1473 $item['location'] = $item['event-location'];
1474 $event['location'] = self::createLocation($item);
1477 // 2021.12: Backward compatibility value, all the events now "adjust" to the viewer timezone
1478 $event['dfrn:adjust'] = true;
1484 * Creates a note/article object array
1486 * @param array $item
1488 * @return array with the object data
1489 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1490 * @throws \ImagickException
1492 public static function createNote($item)
1498 if ($item['event-type'] == 'event') {
1500 } elseif (!empty($item['title'])) {
1506 if ($item['deleted']) {
1507 $type = 'Tombstone';
1511 $data['id'] = $item['uri'];
1512 $data['type'] = $type;
1514 if ($item['deleted']) {
1518 $data['summary'] = BBCode::toPlaintext(BBCode::getAbstract($item['body'], Protocol::ACTIVITYPUB));
1520 if ($item['uri'] != $item['thr-parent']) {
1521 $data['inReplyTo'] = $item['thr-parent'];
1523 $data['inReplyTo'] = null;
1526 $data['diaspora:guid'] = $item['guid'];
1527 $data['published'] = DateTimeFormat::utc($item['created'] . '+00:00', DateTimeFormat::ATOM);
1529 if ($item['created'] != $item['edited']) {
1530 $data['updated'] = DateTimeFormat::utc($item['edited'] . '+00:00', DateTimeFormat::ATOM);
1533 $data['url'] = $item['plink'];
1534 $data['attributedTo'] = $item['author-link'];
1535 $data['sensitive'] = self::isSensitive($item['uri-id']);
1536 $data['context'] = self::fetchContextURLForItem($item);
1538 if (!empty($item['title'])) {
1539 $data['name'] = BBCode::toPlaintext($item['title'], false);
1542 $permission_block = self::createPermissionBlockForItem($item, false);
1544 $body = $item['body'];
1546 if ($type == 'Note') {
1547 $body = $item['raw-body'] ?? self::removePictures($body);
1551 * @todo Improve the automated summary
1552 * This part is currently deactivated. The automated summary seems to be more
1553 * confusing than helping. But possibly we will find a better way.
1554 * So the code is left here for now as a reminder
1556 * } elseif (($type == 'Article') && empty($data['summary'])) {
1557 * $regexp = "/[@!]\[url\=([^\[\]]*)\].*?\[\/url\]/ism";
1558 * $summary = preg_replace_callback($regexp, ['self', 'mentionAddrCallback'], $body);
1559 * $data['summary'] = BBCode::toPlaintext(Plaintext::shorten(self::removePictures($summary), 1000));
1563 if (empty($item['uid']) || !Feature::isEnabled($item['uid'], 'explicit_mentions')) {
1564 $body = self::prependMentions($body, $item['uri-id'], $item['author-link']);
1567 if ($type == 'Event') {
1568 $data = array_merge($data, self::createEvent($item));
1570 $body = BBCode::setMentionsToNicknames($body);
1572 $data['content'] = BBCode::convertForUriId($item['uri-id'], $body, BBCode::ACTIVITYPUB);
1575 // The regular "content" field does contain a minimized HTML. This is done since systems like
1576 // Mastodon has got problems with - for example - embedded pictures.
1577 // The contentMap does contain the unmodified HTML.
1578 $language = self::getLanguage($item);
1579 if (!empty($language)) {
1580 $richbody = BBCode::setMentionsToNicknames($item['body'] ?? '');
1581 $richbody = BBCode::removeAttachment($richbody);
1583 $data['contentMap'][$language] = BBCode::convertForUriId($item['uri-id'], $richbody, BBCode::EXTERNAL);
1586 $data['source'] = ['content' => $item['body'], 'mediaType' => "text/bbcode"];
1588 if (!empty($item['signed_text']) && ($item['uri'] != $item['thr-parent'])) {
1589 $data['diaspora:comment'] = $item['signed_text'];
1592 $data['attachment'] = self::createAttachmentList($item, $type);
1593 $data['tag'] = self::createTagList($item);
1595 if (empty($data['location']) && (!empty($item['coord']) || !empty($item['location']))) {
1596 $data['location'] = self::createLocation($item);
1599 if (!empty($item['app'])) {
1600 $data['generator'] = ['type' => 'Application', 'name' => $item['app']];
1603 $data = array_merge($data, $permission_block);
1609 * Fetches the language from the post, the user or the system.
1611 * @param array $item
1613 * @return string language string
1615 private static function getLanguage(array $item)
1617 // Try to fetch the language from the post itself
1618 if (!empty($item['language'])) {
1619 $languages = array_keys(json_decode($item['language'], true));
1620 if (!empty($languages[0])) {
1621 return $languages[0];
1625 // Otherwise use the user's language
1626 if (!empty($item['uid'])) {
1627 $user = DBA::selectFirst('user', ['language'], ['uid' => $item['uid']]);
1628 if (!empty($user['language'])) {
1629 return $user['language'];
1633 // And finally just use the system language
1634 return DI::config()->get('system', 'language');
1638 * Creates an an "add tag" entry
1640 * @param array $item
1641 * @param array $data activity data
1643 * @return array with activity data for adding tags
1644 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1645 * @throws \ImagickException
1647 private static function createAddTag($item, $data)
1649 $object = XML::parseString($item['object']);
1650 $target = XML::parseString($item["target"]);
1652 $data['diaspora:guid'] = $item['guid'];
1653 $data['actor'] = $item['author-link'];
1654 $data['target'] = (string)$target->id;
1655 $data['summary'] = BBCode::toPlaintext($item['body']);
1656 $data['object'] = ['id' => (string)$object->id, 'type' => 'tag', 'name' => (string)$object->title, 'content' => (string)$object->content];
1662 * Creates an announce object entry
1664 * @param array $item
1665 * @param array $data activity data
1667 * @return array with activity data
1668 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1669 * @throws \ImagickException
1671 private static function createAnnounce($item, $data)
1673 $orig_body = $item['body'];
1674 $announce = self::getAnnounceArray($item);
1675 if (empty($announce)) {
1676 $data['type'] = 'Create';
1677 $data['object'] = self::createNote($item);
1681 if (empty($announce['comment'])) {
1682 // Pure announce, without a quote
1683 $data['type'] = 'Announce';
1684 $data['object'] = $announce['object']['uri'];
1689 $data['type'] = 'Create';
1690 $item['body'] = $announce['comment'] . "\n" . $announce['object']['plink'];
1691 $data['object'] = self::createNote($item);
1693 /// @todo Finally descide how to implement this in AP. This is a possible way:
1694 $data['object']['attachment'][] = self::createNote($announce['object']);
1696 $data['object']['source']['content'] = $orig_body;
1701 * Return announce related data if the item is an annunce
1703 * @param array $item
1707 public static function getAnnounceArray($item)
1709 $reshared = Item::getShareArray($item);
1710 if (empty($reshared['guid'])) {
1714 $reshared_item = Post::selectFirst(Item::DELIVER_FIELDLIST, ['guid' => $reshared['guid']]);
1715 if (!DBA::isResult($reshared_item)) {
1719 if (!in_array($reshared_item['network'], [Protocol::ACTIVITYPUB, Protocol::DFRN])) {
1723 $profile = APContact::getByURL($reshared_item['author-link'], false);
1724 if (empty($profile)) {
1728 return ['object' => $reshared_item, 'actor' => $profile, 'comment' => $reshared['comment']];
1732 * Checks if the provided item array is an announce
1734 * @param array $item
1738 public static function isAnnounce($item)
1740 if (!empty($item['verb']) && ($item['verb'] == Activity::ANNOUNCE)) {
1744 $announce = self::getAnnounceArray($item);
1745 if (empty($announce)) {
1749 return empty($announce['comment']);
1753 * Creates an activity id for a given contact id
1755 * @param integer $cid Contact ID of target
1757 * @return bool|string activity id
1759 public static function activityIDFromContact($cid)
1761 $contact = DBA::selectFirst('contact', ['uid', 'id', 'created'], ['id' => $cid]);
1762 if (!DBA::isResult($contact)) {
1766 $hash = hash('ripemd128', $contact['uid'].'-'.$contact['id'].'-'.$contact['created']);
1767 $uuid = substr($hash, 0, 8). '-' . substr($hash, 8, 4) . '-' . substr($hash, 12, 4) . '-' . substr($hash, 16, 4) . '-' . substr($hash, 20, 12);
1768 return DI::baseUrl() . '/activity/' . $uuid;
1772 * Transmits a contact suggestion to a given inbox
1774 * @param integer $uid User ID
1775 * @param string $inbox Target inbox
1776 * @param integer $suggestion_id Suggestion ID
1778 * @return boolean was the transmission successful?
1779 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1781 public static function sendContactSuggestion($uid, $inbox, $suggestion_id)
1783 $owner = User::getOwnerDataById($uid);
1785 $suggestion = DI::fsuggest()->selectOneById($suggestion_id);
1787 $data = ['@context' => ActivityPub::CONTEXT,
1788 'id' => DI::baseUrl() . '/activity/' . System::createGUID(),
1789 'type' => 'Announce',
1790 'actor' => $owner['url'],
1791 'object' => $suggestion->url,
1792 'content' => $suggestion->note,
1793 'instrument' => self::getService(),
1794 'to' => [ActivityPub::PUBLIC_COLLECTION],
1797 $signed = LDSignature::sign($data, $owner);
1799 Logger::info('Deliver profile deletion for user ' . $uid . ' to ' . $inbox . ' via ActivityPub');
1800 return HTTPSignature::transmit($signed, $inbox, $uid);
1804 * Transmits a profile relocation to a given inbox
1806 * @param integer $uid User ID
1807 * @param string $inbox Target inbox
1809 * @return boolean was the transmission successful?
1810 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1812 public static function sendProfileRelocation($uid, $inbox)
1814 $owner = User::getOwnerDataById($uid);
1816 $data = ['@context' => ActivityPub::CONTEXT,
1817 'id' => DI::baseUrl() . '/activity/' . System::createGUID(),
1818 'type' => 'dfrn:relocate',
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 relocation for user ' . $uid . ' to ' . $inbox . ' via ActivityPub');
1829 return HTTPSignature::transmit($signed, $inbox, $uid);
1833 * Transmits a profile deletion 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 \Friendica\Network\HTTPException\InternalServerErrorException
1841 public static function sendProfileDeletion($uid, $inbox)
1843 $owner = User::getOwnerDataById($uid);
1845 if (empty($owner)) {
1846 Logger::error('No owner data found, the deletion message cannot be processed.', ['user' => $uid]);
1850 if (empty($owner['uprvkey'])) {
1851 Logger::error('No private key for owner found, the deletion message cannot be processed.', ['user' => $uid]);
1855 $data = ['@context' => ActivityPub::CONTEXT,
1856 'id' => DI::baseUrl() . '/activity/' . System::createGUID(),
1858 'actor' => $owner['url'],
1859 'object' => $owner['url'],
1860 'published' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
1861 'instrument' => self::getService(),
1862 'to' => [ActivityPub::PUBLIC_COLLECTION],
1865 $signed = LDSignature::sign($data, $owner);
1867 Logger::info('Deliver profile deletion for user ' . $uid . ' to ' . $inbox . ' via ActivityPub');
1868 return HTTPSignature::transmit($signed, $inbox, $uid);
1872 * Transmits a profile change to a given inbox
1874 * @param integer $uid User ID
1875 * @param string $inbox Target inbox
1877 * @return boolean was the transmission successful?
1878 * @throws HTTPException\InternalServerErrorException
1879 * @throws HTTPException\NotFoundException
1880 * @throws \ImagickException
1882 public static function sendProfileUpdate(int $uid, string $inbox): bool
1884 $owner = User::getOwnerDataById($uid);
1885 $profile = APContact::getByURL($owner['url']);
1887 $data = ['@context' => ActivityPub::CONTEXT,
1888 'id' => DI::baseUrl() . '/activity/' . System::createGUID(),
1890 'actor' => $owner['url'],
1891 'object' => self::getProfile($uid),
1892 'published' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
1893 'instrument' => self::getService(),
1894 'to' => [$profile['followers']],
1897 $signed = LDSignature::sign($data, $owner);
1899 Logger::info('Deliver profile update for user ' . $uid . ' to ' . $inbox . ' via ActivityPub');
1900 return HTTPSignature::transmit($signed, $inbox, $uid);
1904 * Transmits a given activity to a target
1906 * @param string $activity Type name
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 sendActivity($activity, $target, $uid, $id = '')
1916 $profile = APContact::getByURL($target);
1917 if (empty($profile['inbox'])) {
1918 Logger::warning('No inbox found for target', ['target' => $target, 'profile' => $profile]);
1922 $owner = User::getOwnerDataById($uid);
1925 $id = DI::baseUrl() . '/activity/' . System::createGUID();
1928 $data = ['@context' => ActivityPub::CONTEXT,
1930 'type' => $activity,
1931 'actor' => $owner['url'],
1932 'object' => $profile['url'],
1933 'instrument' => self::getService(),
1934 'to' => [$profile['url']]];
1936 Logger::info('Sending activity ' . $activity . ' to ' . $target . ' for user ' . $uid);
1938 $signed = LDSignature::sign($data, $owner);
1939 return HTTPSignature::transmit($signed, $profile['inbox'], $uid);
1943 * Transmits a "follow object" activity to a target
1944 * This is a preparation for sending automated "follow" requests when receiving "Announce" messages
1946 * @param string $object Object URL
1947 * @param string $target Target profile
1948 * @param integer $uid User ID
1950 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1951 * @throws \ImagickException
1952 * @throws \Exception
1954 public static function sendFollowObject($object, $target, $uid = 0)
1956 $profile = APContact::getByURL($target);
1957 if (empty($profile['inbox'])) {
1958 Logger::warning('No inbox found for target', ['target' => $target, 'profile' => $profile]);
1963 // Fetch the list of administrators
1964 $admin_mail = explode(',', str_replace(' ', '', DI::config()->get('config', 'admin_email')));
1966 // We need to use some user as a sender. It doesn't care who it will send. We will use an administrator account.
1967 $condition = ['verified' => true, 'blocked' => false, 'account_removed' => false, 'account_expired' => false, 'email' => $admin_mail];
1968 $first_user = DBA::selectFirst('user', ['uid'], $condition);
1969 $uid = $first_user['uid'];
1972 $condition = ['verb' => Activity::FOLLOW, 'uid' => 0, 'parent-uri' => $object,
1973 'author-id' => Contact::getPublicIdByUserId($uid)];
1974 if (Post::exists($condition)) {
1975 Logger::info('Follow for ' . $object . ' for user ' . $uid . ' does already exist.');
1979 $owner = User::getOwnerDataById($uid);
1981 $data = ['@context' => ActivityPub::CONTEXT,
1982 'id' => DI::baseUrl() . '/activity/' . System::createGUID(),
1984 'actor' => $owner['url'],
1985 'object' => $object,
1986 'instrument' => self::getService(),
1987 'to' => [$profile['url']]];
1989 Logger::info('Sending follow ' . $object . ' to ' . $target . ' for user ' . $uid);
1991 $signed = LDSignature::sign($data, $owner);
1992 return HTTPSignature::transmit($signed, $profile['inbox'], $uid);
1996 * Transmit a message that the contact request had been accepted
1998 * @param string $target Target profile
2000 * @param integer $uid User ID
2001 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2002 * @throws \ImagickException
2004 public static function sendContactAccept($target, $id, $uid)
2006 $profile = APContact::getByURL($target);
2007 if (empty($profile['inbox'])) {
2008 Logger::warning('No inbox found for target', ['target' => $target, 'profile' => $profile]);
2012 $owner = User::getOwnerDataById($uid);
2013 $data = ['@context' => ActivityPub::CONTEXT,
2014 'id' => DI::baseUrl() . '/activity/' . System::createGUID(),
2016 'actor' => $owner['url'],
2018 'id' => (string)$id,
2020 'actor' => $profile['url'],
2021 'object' => $owner['url']
2023 'instrument' => self::getService(),
2024 'to' => [$profile['url']]];
2026 Logger::debug('Sending accept to ' . $target . ' for user ' . $uid . ' with id ' . $id);
2028 $signed = LDSignature::sign($data, $owner);
2029 HTTPSignature::transmit($signed, $profile['inbox'], $uid);
2033 * Reject a contact request or terminates the contact relation
2035 * @param string $target Target profile
2037 * @param integer $uid User ID
2038 * @return bool Operation success
2039 * @throws HTTPException\InternalServerErrorException
2040 * @throws \ImagickException
2042 public static function sendContactReject($target, $id, $uid): bool
2044 $profile = APContact::getByURL($target);
2045 if (empty($profile['inbox'])) {
2046 Logger::warning('No inbox found for target', ['target' => $target, 'profile' => $profile]);
2050 $owner = User::getOwnerDataById($uid);
2051 $data = ['@context' => ActivityPub::CONTEXT,
2052 'id' => DI::baseUrl() . '/activity/' . System::createGUID(),
2054 'actor' => $owner['url'],
2056 'id' => (string)$id,
2058 'actor' => $profile['url'],
2059 'object' => $owner['url']
2061 'instrument' => self::getService(),
2062 'to' => [$profile['url']]];
2064 Logger::debug('Sending reject to ' . $target . ' for user ' . $uid . ' with id ' . $id);
2066 $signed = LDSignature::sign($data, $owner);
2067 return HTTPSignature::transmit($signed, $profile['inbox'], $uid);
2071 * Transmits a message that we don't want to follow this contact anymore
2073 * @param string $target Target profile
2074 * @param integer $uid User ID
2075 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2076 * @throws \ImagickException
2077 * @throws \Exception
2078 * @return bool success
2080 public static function sendContactUndo($target, $cid, $uid)
2082 $profile = APContact::getByURL($target);
2083 if (empty($profile['inbox'])) {
2084 Logger::warning('No inbox found for target', ['target' => $target, 'profile' => $profile]);
2088 $object_id = self::activityIDFromContact($cid);
2089 if (empty($object_id)) {
2093 $id = DI::baseUrl() . '/activity/' . System::createGUID();
2095 $owner = User::getOwnerDataById($uid);
2096 $data = ['@context' => ActivityPub::CONTEXT,
2099 'actor' => $owner['url'],
2100 'object' => ['id' => $object_id, 'type' => 'Follow',
2101 'actor' => $owner['url'],
2102 'object' => $profile['url']],
2103 'instrument' => self::getService(),
2104 'to' => [$profile['url']]];
2106 Logger::info('Sending undo to ' . $target . ' for user ' . $uid . ' with id ' . $id);
2108 $signed = LDSignature::sign($data, $owner);
2109 return HTTPSignature::transmit($signed, $profile['inbox'], $uid);
2112 private static function prependMentions($body, int $uriid, string $authorLink)
2116 foreach (Tag::getByURIId($uriid, [Tag::IMPLICIT_MENTION]) as $tag) {
2117 $profile = Contact::getByURL($tag['url'], false, ['addr', 'contact-type', 'nick']);
2118 if (!empty($profile['addr'])
2119 && $profile['contact-type'] != Contact::TYPE_COMMUNITY
2120 && !strstr($body, $profile['addr'])
2121 && !strstr($body, $tag['url'])
2122 && $tag['url'] !== $authorLink
2124 $mentions[] = '@[url=' . $tag['url'] . ']' . $profile['nick'] . '[/url]';
2128 $mentions[] = $body;
2130 return implode(' ', $mentions);