3 * @copyright Copyright (C) 2010-2021, 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\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 DBA::update('contact', ['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 DBA::update('contact', ['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'],
169 $condition = DBA::buildCondition($parameters);
171 $sql = "SELECT COUNT(*) as `count`
173 JOIN `apcontact` ON `apcontact`.`url` = `contact`.`url`
176 $contacts = DBA::fetchFirst($sql, ...$parameters);
178 $modulePath = '/' . $module . '/';
180 $data = ['@context' => ActivityPub::CONTEXT];
181 $data['id'] = DI::baseUrl() . $modulePath . $owner['nickname'];
182 $data['type'] = 'OrderedCollection';
183 $data['totalItems'] = $contacts['count'];
185 // When we hide our friends we will only show the pure number but don't allow more.
186 $profile = Profile::getByUID($owner['uid']);
187 if (!empty($profile['hide-friends'])) {
192 $data['first'] = DI::baseUrl() . $modulePath . $owner['nickname'] . '?page=1';
194 $data['type'] = 'OrderedCollectionPage';
197 $sql = "SELECT `contact`.`url`
199 JOIN `apcontact` ON `apcontact`.`url` = `contact`.`url`
203 $parameters[] = ($page - 1) * 100;
206 $contacts = DBA::p($sql, ...$parameters);
207 while ($contact = DBA::fetch($contacts)) {
208 $list[] = $contact['url'];
210 DBA::close($contacts);
213 $data['next'] = DI::baseUrl() . $modulePath . $owner['nickname'] . '?page=' . ($page + 1);
216 $data['partOf'] = DI::baseUrl() . $modulePath . $owner['nickname'];
218 $data['orderedItems'] = $list;
225 * Public posts for the given owner
227 * @param array $owner Owner array
228 * @param integer $page Page number
229 * @param string $requester URL of requesting account
231 * @return array of posts
232 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
233 * @throws \ImagickException
235 public static function getOutbox($owner, $page = null, $requester = '')
237 $condition = ['private' => [Item::PUBLIC, Item::UNLISTED]];
239 if (!empty($requester)) {
240 $requester_id = Contact::getIdForURL($requester, $owner['uid']);
241 if (!empty($requester_id)) {
242 $permissionSets = DI::permissionSet()->selectByContactId($requester_id, $owner['uid']);
243 if (!empty($permissionSets)) {
244 $condition = ['psid' => array_merge($permissionSets->column('id'),
245 [DI::permissionSet()->getIdFromACL($owner['uid'], '', '', '', '')])];
250 $condition = array_merge($condition,
251 ['uid' => $owner['uid'],
252 'author-id' => Contact::getIdForURL($owner['url'], 0, false),
253 'gravity' => [GRAVITY_PARENT, GRAVITY_COMMENT],
254 'network' => Protocol::FEDERATED,
255 'parent-network' => Protocol::FEDERATED,
260 $count = Post::count($condition);
262 $data = ['@context' => ActivityPub::CONTEXT];
263 $data['id'] = DI::baseUrl() . '/outbox/' . $owner['nickname'];
264 $data['type'] = 'OrderedCollection';
265 $data['totalItems'] = $count;
268 $data['first'] = DI::baseUrl() . '/outbox/' . $owner['nickname'] . '?page=1';
270 $data['type'] = 'OrderedCollectionPage';
273 $items = Post::select(['id'], $condition, ['limit' => [($page - 1) * 20, 20], 'order' => ['created' => true]]);
274 while ($item = Post::fetch($items)) {
275 $activity = self::createActivityFromItem($item['id'], true);
276 $activity['type'] = $activity['type'] == 'Update' ? 'Create' : $activity['type'];
278 // Only list "Create" activity objects here, no reshares
279 if (!empty($activity['object']) && ($activity['type'] == 'Create')) {
280 $list[] = $activity['object'];
286 $data['next'] = DI::baseUrl() . '/outbox/' . $owner['nickname'] . '?page=' . ($page + 1);
289 $data['partOf'] = DI::baseUrl() . '/outbox/' . $owner['nickname'];
291 $data['orderedItems'] = $list;
298 * Return the service array containing information the used software and it's url
300 * @return array with service data
302 private static function getService()
304 return ['type' => 'Service',
305 'name' => FRIENDICA_PLATFORM . " '" . FRIENDICA_CODENAME . "' " . FRIENDICA_VERSION . '-' . DB_UPDATE_VERSION,
306 'url' => DI::baseUrl()->get()];
310 * Return the ActivityPub profile of the given user
312 * @param int $uid User ID
313 * @return array with profile data
314 * @throws HTTPException\NotFoundException
315 * @throws HTTPException\InternalServerErrorException
317 public static function getProfile(int $uid): array
319 $owner = User::getOwnerDataById($uid);
320 if (!isset($owner['id'])) {
321 DI::logger()->error('Unable to find owner data for uid', ['uid' => $uid, 'callstack' => System::callstack(20)]);
322 throw new HTTPException\NotFoundException('User not found.');
325 $data = ['@context' => ActivityPub::CONTEXT];
326 $data['id'] = $owner['url'];
328 if (!empty($owner['guid'])) {
329 $data['diaspora:guid'] = $owner['guid'];
332 $data['type'] = ActivityPub::ACCOUNT_TYPES[$owner['account-type']];
335 $data['following'] = DI::baseUrl() . '/following/' . $owner['nick'];
336 $data['followers'] = DI::baseUrl() . '/followers/' . $owner['nick'];
337 $data['inbox'] = DI::baseUrl() . '/inbox/' . $owner['nick'];
338 $data['outbox'] = DI::baseUrl() . '/outbox/' . $owner['nick'];
340 $data['inbox'] = DI::baseUrl() . '/friendica/inbox';
343 $data['preferredUsername'] = $owner['nick'];
344 $data['name'] = $owner['name'];
346 if (!empty($owner['country-name'] . $owner['region'] . $owner['locality'])) {
347 $data['vcard:hasAddress'] = ['@type' => 'vcard:Home', 'vcard:country-name' => $owner['country-name'],
348 'vcard:region' => $owner['region'], 'vcard:locality' => $owner['locality']];
351 if (!empty($owner['about'])) {
352 $data['summary'] = BBCode::convertForUriId($owner['uri-id'] ?? 0, $owner['about'], BBCode::EXTERNAL);
355 if (!empty($owner['xmpp']) || !empty($owner['matrix'])) {
356 $data['vcard:hasInstantMessage'] = [];
358 if (!empty($owner['xmpp'])) {
359 $data['vcard:hasInstantMessage'][] = 'xmpp:' . $owner['xmpp'];
361 if (!empty($owner['matrix'])) {
362 $data['vcard:hasInstantMessage'][] = 'matrix:' . $owner['matrix'];
366 $data['url'] = $owner['url'];
367 $data['manuallyApprovesFollowers'] = in_array($owner['page-flags'], [User::PAGE_FLAGS_NORMAL, User::PAGE_FLAGS_PRVGROUP]);
368 $data['discoverable'] = (bool)$owner['net-publish'];
369 $data['publicKey'] = ['id' => $owner['url'] . '#main-key',
370 'owner' => $owner['url'],
371 'publicKeyPem' => $owner['pubkey']];
372 $data['endpoints'] = ['sharedInbox' => DI::baseUrl() . '/inbox'];
373 $data['icon'] = ['type' => 'Image', 'url' => Contact::getAvatarUrlForId($owner['id'], '', $owner['updated'])];
375 $resourceid = Photo::ridFromURI($owner['photo']);
376 if (!empty($resourceid)) {
377 $photo = Photo::selectFirst(['type'], ["resource-id" => $resourceid]);
378 if (!empty($photo['type'])) {
379 $data['icon']['mediaType'] = $photo['type'];
383 if (!empty($owner['header'])) {
384 $data['image'] = ['type' => 'Image', 'url' => Contact::getHeaderUrlForId($owner['id'], '', $owner['updated'])];
386 $resourceid = Photo::ridFromURI($owner['header']);
387 if (!empty($resourceid)) {
388 $photo = Photo::selectFirst(['type'], ["resource-id" => $resourceid]);
389 if (!empty($photo['type'])) {
390 $data['image']['mediaType'] = $photo['type'];
395 $data['generator'] = self::getService();
397 // tags: https://kitty.town/@inmysocks/100656097926961126.json
402 * @param string $username
404 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
406 public static function getDeletedUser($username)
409 '@context' => ActivityPub::CONTEXT,
410 'id' => DI::baseUrl() . '/profile/' . $username,
411 'type' => 'Tombstone',
412 'published' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
413 'updated' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
414 'deleted' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
419 * Returns an array with permissions of a given item array
423 * @return array with permissions
424 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
425 * @throws \ImagickException
427 private static function fetchPermissionBlockFromConversation($item)
429 if (empty($item['thr-parent'])) {
433 $condition = ['item-uri' => $item['thr-parent'], 'protocol' => Conversation::PARCEL_ACTIVITYPUB];
434 $conversation = DBA::selectFirst('conversation', ['source'], $condition);
435 if (!DBA::isResult($conversation)) {
439 $activity = json_decode($conversation['source'], true);
441 $actor = JsonLD::fetchElement($activity, 'actor', 'id');
442 if (!empty($actor)) {
443 $permissions['to'][] = $actor;
444 $profile = APContact::getByURL($actor);
449 $item_profile = APContact::getByURL($item['author-link']);
450 $exclude[] = $item['author-link'];
452 if ($item['gravity'] == GRAVITY_PARENT) {
453 $exclude[] = $item['owner-link'];
456 foreach (['to', 'cc', 'bto', 'bcc'] as $element) {
457 if (empty($activity[$element])) {
460 if (is_string($activity[$element])) {
461 $activity[$element] = [$activity[$element]];
464 foreach ($activity[$element] as $receiver) {
465 if (empty($receiver)) {
469 if (!empty($profile['followers']) && $receiver == $profile['followers'] && !empty($item_profile['followers'])) {
470 $permissions[$element][] = $item_profile['followers'];
471 } elseif (!in_array($receiver, $exclude)) {
472 $permissions[$element][] = $receiver;
480 * Check if the given item id is from ActivityPub
482 * @param integer $item_id
483 * @return boolean "true" if the post is from ActivityPub
485 private static function isAPPost(int $item_id)
487 if (empty($item_id)) {
491 return Post::exists(['id' => $item_id, 'network' => Protocol::ACTIVITYPUB]);
495 * Creates an array of permissions from an item thread
497 * @param array $item Item array
498 * @param boolean $blindcopy addressing via "bcc" or "cc"?
499 * @param integer $last_id Last item id for adding receivers
500 * @param boolean $forum_mode "true" means that we are sending content to a forum
502 * @return array with permission data
503 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
504 * @throws \ImagickException
506 private static function createPermissionBlockForItem($item, $blindcopy, $last_id = 0, $forum_mode = false)
509 $last_id = $item['id'];
514 // Check if we should always deliver our stuff via BCC
515 if (!empty($item['uid'])) {
516 $profile = User::getOwnerDataById($item['uid']);
517 if (!empty($profile)) {
518 $always_bcc = $profile['hide-friends'];
522 if (DI::config()->get('system', 'ap_always_bcc')) {
526 if (self::isAnnounce($item) || DI::config()->get('debug', 'total_ap_delivery') || self::isAPPost($last_id)) {
527 // Will be activated in a later step
528 $networks = Protocol::FEDERATED;
530 // For now only send to these contacts:
531 $networks = [Protocol::ACTIVITYPUB, Protocol::OSTATUS];
534 $data = ['to' => [], 'cc' => [], 'bcc' => []];
536 if ($item['gravity'] == GRAVITY_PARENT) {
537 $actor_profile = APContact::getByURL($item['owner-link']);
539 $actor_profile = APContact::getByURL($item['author-link']);
544 $terms = Tag::getByURIId($item['uri-id'], [Tag::MENTION, Tag::IMPLICIT_MENTION, Tag::EXCLUSIVE_MENTION]);
546 if ($item['private'] != Item::PRIVATE) {
547 // Directly mention the original author upon a quoted reshare.
548 // Else just ensure that the original author receives the reshare.
549 $announce = self::getAnnounceArray($item);
550 if (!empty($announce['comment'])) {
551 $data['to'][] = $announce['actor']['url'];
552 } elseif (!empty($announce)) {
553 $data['cc'][] = $announce['actor']['url'];
556 $data = array_merge($data, self::fetchPermissionBlockFromConversation($item));
558 // Check if the item is completely public or unlisted
559 if ($item['private'] == Item::PUBLIC) {
560 $data['to'][] = ActivityPub::PUBLIC_COLLECTION;
562 $data['cc'][] = ActivityPub::PUBLIC_COLLECTION;
565 foreach ($terms as $term) {
566 $profile = APContact::getByURL($term['url'], false);
567 if (!empty($profile)) {
568 if ($term['type'] == Tag::EXCLUSIVE_MENTION) {
570 if (!empty($profile['followers']) && ($profile['type'] == 'Group')) {
571 $data['cc'][] = $profile['followers'];
574 $data['to'][] = $profile['url'];
578 $receiver_list = Item::enumeratePermissions($item, true);
580 foreach ($terms as $term) {
581 $cid = Contact::getIdForURL($term['url'], $item['uid']);
582 if (!empty($cid) && in_array($cid, $receiver_list)) {
583 $contact = DBA::selectFirst('contact', ['url', 'network', 'protocol', 'gsid'], ['id' => $cid, 'network' => Protocol::FEDERATED]);
584 if (!DBA::isResult($contact) || !self::isAPContact($contact, $networks)) {
588 if (!empty($profile = APContact::getByURL($contact['url'], false))) {
589 $data['to'][] = $profile['url'];
594 foreach ($receiver_list as $receiver) {
595 $contact = DBA::selectFirst('contact', ['url', 'hidden', 'network', 'protocol', 'gsid'], ['id' => $receiver, 'network' => Protocol::FEDERATED]);
596 if (!DBA::isResult($contact) || !self::isAPContact($contact, $networks)) {
600 if (!empty($profile = APContact::getByURL($contact['url'], false))) {
601 if ($contact['hidden'] || $always_bcc) {
602 $data['bcc'][] = $profile['url'];
604 $data['cc'][] = $profile['url'];
610 if (!empty($item['parent'])) {
611 $parents = Post::select(['id', 'author-link', 'owner-link', 'gravity', 'uri'], ['parent' => $item['parent']]);
612 while ($parent = Post::fetch($parents)) {
613 if ($parent['gravity'] == GRAVITY_PARENT) {
614 $profile = APContact::getByURL($parent['owner-link'], false);
615 if (!empty($profile)) {
616 if ($item['gravity'] != GRAVITY_PARENT) {
617 // Comments to forums are directed to the forum
618 // But comments to forums aren't directed to the followers collection
619 // This rule is only valid when the actor isn't the forum.
620 // The forum needs to transmit their content to their followers.
621 if (($profile['type'] == 'Group') && ($profile['url'] != ($actor_profile['url'] ?? ''))) {
622 $data['to'][] = $profile['url'];
624 $data['cc'][] = $profile['url'];
625 if (($item['private'] != Item::PRIVATE) && !empty($actor_profile['followers'])) {
626 $data['cc'][] = $actor_profile['followers'];
629 } elseif (!$exclusive) {
630 // Public thread parent post always are directed to the followers.
631 // This mustn't be done by posts that are directed to forum servers via the exclusive mention.
632 // But possibly in that case we could add the "followers" collection of the forum to the message.
633 if (($item['private'] != Item::PRIVATE) && !$forum_mode) {
634 $data['cc'][] = $actor_profile['followers'];
640 // Don't include data from future posts
641 if ($parent['id'] >= $last_id) {
645 $profile = APContact::getByURL($parent['author-link'], false);
646 if (!empty($profile)) {
647 if (($profile['type'] == 'Group') || ($parent['uri'] == $item['thr-parent'])) {
648 $data['to'][] = $profile['url'];
650 $data['cc'][] = $profile['url'];
654 DBA::close($parents);
657 $data['to'] = array_unique($data['to']);
658 $data['cc'] = array_unique($data['cc']);
659 $data['bcc'] = array_unique($data['bcc']);
661 if (($key = array_search($item['author-link'], $data['to'])) !== false) {
662 unset($data['to'][$key]);
665 if (($key = array_search($item['author-link'], $data['cc'])) !== false) {
666 unset($data['cc'][$key]);
669 if (($key = array_search($item['author-link'], $data['bcc'])) !== false) {
670 unset($data['bcc'][$key]);
673 foreach ($data['to'] as $to) {
674 if (($key = array_search($to, $data['cc'])) !== false) {
675 unset($data['cc'][$key]);
678 if (($key = array_search($to, $data['bcc'])) !== false) {
679 unset($data['bcc'][$key]);
683 foreach ($data['cc'] as $cc) {
684 if (($key = array_search($cc, $data['bcc'])) !== false) {
685 unset($data['bcc'][$key]);
689 $receivers = ['to' => array_values($data['to']), 'cc' => array_values($data['cc']), 'bcc' => array_values($data['bcc'])];
692 unset($receivers['bcc']);
699 * Check if an inbox is archived
701 * @param string $url Inbox url
703 * @return boolean "true" if inbox is archived
705 public static function archivedInbox($url)
707 return DBA::exists('inbox-status', ['url' => $url, 'archive' => true]);
711 * Check if a given contact should be delivered via AP
713 * @param array $contact
714 * @param array $networks
718 private static function isAPContact(array $contact, array $networks)
720 if (in_array($contact['network'], $networks) || ($contact['protocol'] == Protocol::ACTIVITYPUB)) {
724 return GServer::getProtocol($contact['gsid'] ?? 0) == Post\DeliveryData::ACTIVITYPUB;
728 * Fetches a list of inboxes of followers of a given user
730 * @param integer $uid User ID
731 * @param boolean $personal fetch personal inboxes
732 * @param boolean $all_ap Retrieve all AP enabled inboxes
734 * @return array of follower inboxes
735 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
736 * @throws \ImagickException
738 public static function fetchTargetInboxesforUser($uid, $personal = false, bool $all_ap = false)
744 if (!empty($item['uid'])) {
745 $profile = User::getOwnerDataById($item['uid']);
746 if (!empty($profile)) {
747 $isforum = $profile['account-type'] == User::ACCOUNT_TYPE_COMMUNITY;
751 if (DI::config()->get('debug', 'total_ap_delivery') || $all_ap) {
752 // Will be activated in a later step
753 $networks = Protocol::FEDERATED;
755 // For now only send to these contacts:
756 $networks = [Protocol::ACTIVITYPUB, Protocol::OSTATUS];
759 $condition = ['uid' => $uid, 'archive' => false, 'pending' => false, 'blocked' => false, 'network' => Protocol::FEDERATED];
762 $condition['rel'] = [Contact::FOLLOWER, Contact::FRIEND];
765 $contacts = DBA::select('contact', ['id', 'url', 'network', 'protocol', 'gsid'], $condition);
766 while ($contact = DBA::fetch($contacts)) {
767 if (!self::isAPContact($contact, $networks)) {
771 if ($isforum && ($contact['network'] == Protocol::DFRN)) {
775 if (Network::isUrlBlocked($contact['url'])) {
779 $profile = APContact::getByURL($contact['url'], false);
780 if (!empty($profile)) {
781 if (empty($profile['sharedinbox']) || $personal || Contact::isLocal($contact['url'])) {
782 $target = $profile['inbox'];
784 $target = $profile['sharedinbox'];
786 if (!self::archivedInbox($target)) {
787 $inboxes[$target][] = $contact['id'];
791 DBA::close($contacts);
797 * Fetches an array of inboxes for the given item and user
799 * @param array $item Item array
800 * @param integer $uid User ID
801 * @param boolean $personal fetch personal inboxes
802 * @param integer $last_id Last item id for adding receivers
803 * @param boolean $forum_mode "true" means that we are sending content to a forum
804 * @return array with inboxes
805 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
806 * @throws \ImagickException
808 public static function fetchTargetInboxes($item, $uid, $personal = false, $last_id = 0, $forum_mode = false)
810 $permissions = self::createPermissionBlockForItem($item, true, $last_id, $forum_mode);
811 if (empty($permissions)) {
817 if ($item['gravity'] == GRAVITY_ACTIVITY) {
818 $item_profile = APContact::getByURL($item['author-link'], false);
820 $item_profile = APContact::getByURL($item['owner-link'], false);
823 if (empty($item_profile)) {
827 $profile_uid = User::getIdForURL($item_profile['url']);
829 foreach (['to', 'cc', 'bto', 'bcc'] as $element) {
830 if (empty($permissions[$element])) {
834 $blindcopy = in_array($element, ['bto', 'bcc']);
836 foreach ($permissions[$element] as $receiver) {
837 if (empty($receiver) || Network::isUrlBlocked($receiver)) {
841 if ($item_profile && ($receiver == $item_profile['followers']) && ($uid == $profile_uid)) {
842 $inboxes = array_merge($inboxes, self::fetchTargetInboxesforUser($uid, $personal, self::isAPPost($last_id)));
844 $profile = APContact::getByURL($receiver, false);
845 if (!empty($profile)) {
846 $contact = Contact::getByURLForUser($receiver, $uid, false, ['id']);
848 if (empty($profile['sharedinbox']) || $personal || $blindcopy || Contact::isLocal($receiver)) {
849 $target = $profile['inbox'];
851 $target = $profile['sharedinbox'];
853 if (!self::archivedInbox($target)) {
854 $inboxes[$target][] = $contact['id'] ?? 0;
865 * Creates an array in the structure of the item table for a given mail id
867 * @param integer $mail_id
872 public static function ItemArrayFromMail($mail_id, $use_title = false)
874 $mail = DBA::selectFirst('mail', [], ['id' => $mail_id]);
875 if (!DBA::isResult($mail)) {
879 $reply = DBA::selectFirst('mail', ['uri', 'uri-id', 'from-url'], ['parent-uri' => $mail['parent-uri'], 'reply' => false]);
880 if (!DBA::isResult($reply)) {
884 // Making the post more compatible for Mastodon by:
885 // - Making it a note and not an article (no title)
886 // - Moving the title into the "summary" field that is used as a "content warning"
889 $mail['body'] = '[abstract]' . $mail['title'] . "[/abstract]\n" . $mail['body'];
893 $mail['author-link'] = $mail['owner-link'] = $mail['from-url'];
894 $mail['owner-id'] = $mail['author-id'];
895 $mail['allow_cid'] = '<'.$mail['contact-id'].'>';
896 $mail['allow_gid'] = '';
897 $mail['deny_cid'] = '';
898 $mail['deny_gid'] = '';
899 $mail['private'] = Item::PRIVATE;
900 $mail['deleted'] = false;
901 $mail['edited'] = $mail['created'];
902 $mail['plink'] = DI::baseUrl() . '/message/' . $mail['id'];
903 $mail['parent-uri'] = $reply['uri'];
904 $mail['parent-uri-id'] = $reply['uri-id'];
905 $mail['parent-author-id'] = Contact::getIdForURL($reply['from-url'], 0, false);
906 $mail['gravity'] = ($mail['reply'] ? GRAVITY_COMMENT: GRAVITY_PARENT);
907 $mail['event-type'] = '';
908 $mail['language'] = '';
915 * Creates an activity array for a given mail id
917 * @param integer $mail_id
918 * @param boolean $object_mode Is the activity item is used inside another object?
920 * @return array of activity
923 public static function createActivityFromMail($mail_id, $object_mode = false)
925 $mail = self::ItemArrayFromMail($mail_id);
929 $object = self::createNote($mail);
932 $data = ['@context' => ActivityPub::CONTEXT];
937 $data['id'] = $mail['uri'] . '/Create';
938 $data['type'] = 'Create';
939 $data['actor'] = $mail['author-link'];
940 $data['published'] = DateTimeFormat::utc($mail['created'] . '+00:00', DateTimeFormat::ATOM);
941 $data['instrument'] = self::getService();
942 $data = array_merge($data, self::createPermissionBlockForItem($mail, true));
944 if (empty($data['to']) && !empty($data['cc'])) {
945 $data['to'] = $data['cc'];
948 if (empty($data['to']) && !empty($data['bcc'])) {
949 $data['to'] = $data['bcc'];
955 $object['to'] = $data['to'];
956 $object['tag'] = [['type' => 'Mention', 'href' => $object['to'][0], 'name' => '']];
958 unset($object['cc']);
959 unset($object['bcc']);
961 $data['directMessage'] = true;
963 $data['object'] = $object;
965 $owner = User::getOwnerDataById($mail['uid']);
967 if (!$object_mode && !empty($owner)) {
968 return LDSignature::sign($data, $owner);
975 * Returns the activity type of a given item
979 * @return string with activity type
980 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
981 * @throws \ImagickException
983 private static function getTypeOfItem($item)
987 // Only check for a reshare, if it is a real reshare and no quoted reshare
988 if (strpos($item['body'], "[share") === 0) {
989 $announce = self::getAnnounceArray($item);
990 $reshared = !empty($announce);
995 } elseif ($item['verb'] == Activity::POST) {
996 if ($item['created'] == $item['edited']) {
1001 } elseif ($item['verb'] == Activity::LIKE) {
1003 } elseif ($item['verb'] == Activity::DISLIKE) {
1005 } elseif ($item['verb'] == Activity::ATTEND) {
1007 } elseif ($item['verb'] == Activity::ATTENDNO) {
1009 } elseif ($item['verb'] == Activity::ATTENDMAYBE) {
1010 $type = 'TentativeAccept';
1011 } elseif ($item['verb'] == Activity::FOLLOW) {
1013 } elseif ($item['verb'] == Activity::TAG) {
1015 } elseif ($item['verb'] == Activity::ANNOUNCE) {
1025 * Creates the activity or fetches it from the cache
1027 * @param integer $item_id
1028 * @param boolean $force Force new cache entry
1030 * @return array with the activity
1031 * @throws \Exception
1033 public static function createCachedActivityFromItem($item_id, $force = false)
1035 $cachekey = 'APDelivery:createActivity:' . $item_id;
1038 $data = DI::cache()->get($cachekey);
1039 if (!is_null($data)) {
1044 $data = self::createActivityFromItem($item_id);
1046 DI::cache()->set($cachekey, $data, Duration::QUARTER_HOUR);
1051 * Creates an activity array for a given item id
1053 * @param integer $item_id
1054 * @param boolean $object_mode Is the activity item is used inside another object?
1056 * @return false|array
1057 * @throws \Exception
1059 public static function createActivityFromItem(int $item_id, bool $object_mode = false)
1061 Logger::info('Fetching activity', ['item' => $item_id]);
1062 $item = Post::selectFirst(Item::DELIVER_FIELDLIST, ['id' => $item_id, 'parent-network' => Protocol::NATIVE_SUPPORT]);
1063 if (!DBA::isResult($item)) {
1067 // In case of a forum post ensure to return the original post if author and forum are on the same machine
1068 if (($item['gravity'] == GRAVITY_PARENT) && !empty($item['forum_mode'])) {
1069 $author = Contact::getById($item['author-id'], ['nurl']);
1070 if (!empty($author['nurl'])) {
1071 $self = Contact::selectFirst(['uid'], ['nurl' => $author['nurl'], 'self' => true]);
1072 if (!empty($self['uid'])) {
1073 $forum_item = Post::selectFirst(Item::DELIVER_FIELDLIST, ['uri-id' => $item['uri-id'], 'uid' => $self['uid']]);
1074 if (DBA::isResult($forum_item)) {
1075 $item = $forum_item;
1081 if (empty($item['uri-id'])) {
1082 Logger::warning('Item without uri-id', ['item' => $item]);
1086 if (!$item['deleted']) {
1087 $condition = ['item-uri' => $item['uri'], 'protocol' => Conversation::PARCEL_ACTIVITYPUB];
1088 $conversation = DBA::selectFirst('conversation', ['source'], $condition);
1089 if (!$item['origin'] && DBA::isResult($conversation)) {
1090 $data = json_decode($conversation['source'], true);
1091 if (!empty($data['type'])) {
1092 if (in_array($data['type'], ['Create', 'Update'])) {
1094 unset($data['@context']);
1095 unset($data['signature']);
1097 Logger::info('Return stored conversation', ['item' => $item_id]);
1099 } elseif (in_array('as:' . $data['type'], Receiver::CONTENT_TYPES)) {
1100 if (!empty($data['@context'])) {
1101 $context = $data['@context'];
1102 unset($data['@context']);
1104 unset($data['actor']);
1111 $type = self::getTypeOfItem($item);
1113 if (!$object_mode) {
1114 $data = ['@context' => $context ?? ActivityPub::CONTEXT];
1116 if ($item['deleted'] && ($item['gravity'] == GRAVITY_ACTIVITY)) {
1118 } elseif ($item['deleted']) {
1125 if ($type == 'Delete') {
1126 $data['id'] = Item::newURI($item['uid'], $item['guid']) . '/' . $type;;
1127 } elseif (($item['gravity'] == GRAVITY_ACTIVITY) && ($type != 'Undo')) {
1128 $data['id'] = $item['uri'];
1130 $data['id'] = $item['uri'] . '/' . $type;
1133 $data['type'] = $type;
1135 if (($type != 'Announce') || ($item['gravity'] != GRAVITY_PARENT)) {
1136 $data['actor'] = $item['author-link'];
1138 $data['actor'] = $item['owner-link'];
1141 $data['published'] = DateTimeFormat::utc($item['created'] . '+00:00', DateTimeFormat::ATOM);
1143 $data['instrument'] = self::getService();
1145 $data = array_merge($data, self::createPermissionBlockForItem($item, false));
1147 if (in_array($data['type'], ['Create', 'Update', 'Delete'])) {
1148 $data['object'] = $object ?? self::createNote($item);
1149 } elseif ($data['type'] == 'Add') {
1150 $data = self::createAddTag($item, $data);
1151 } elseif ($data['type'] == 'Announce') {
1152 if ($item['verb'] == ACTIVITY::ANNOUNCE) {
1153 $data['object'] = $item['thr-parent'];
1155 $data = self::createAnnounce($item, $data);
1157 } elseif ($data['type'] == 'Follow') {
1158 $data['object'] = $item['parent-uri'];
1159 } elseif ($data['type'] == 'Undo') {
1160 $data['object'] = self::createActivityFromItem($item_id, true);
1162 $data['diaspora:guid'] = $item['guid'];
1163 if (!empty($item['signed_text'])) {
1164 $data['diaspora:like'] = $item['signed_text'];
1166 $data['object'] = $item['thr-parent'];
1169 if (!empty($item['contact-uid'])) {
1170 $uid = $item['contact-uid'];
1172 $uid = $item['uid'];
1175 $owner = User::getOwnerDataById($uid);
1177 Logger::info('Fetched activity', ['item' => $item_id, 'uid' => $uid]);
1179 // We don't sign if we aren't the actor. This is important for relaying content especially for forums
1180 if (!$object_mode && !empty($owner) && ($data['actor'] == $owner['url'])) {
1181 return LDSignature::sign($data, $owner);
1186 /// @todo Create "conversation" entry
1190 * Creates a location entry for a given item array
1192 * @param array $item
1194 * @return array with location array
1196 private static function createLocation($item)
1198 $location = ['type' => 'Place'];
1200 if (!empty($item['location'])) {
1201 $location['name'] = $item['location'];
1206 if (empty($item['coord'])) {
1207 $coord = Map::getCoordinates($item['location']);
1209 $coords = explode(' ', $item['coord']);
1210 if (count($coords) == 2) {
1211 $coord = ['lat' => $coords[0], 'lon' => $coords[1]];
1215 if (!empty($coord['lat']) && !empty($coord['lon'])) {
1216 $location['latitude'] = $coord['lat'];
1217 $location['longitude'] = $coord['lon'];
1224 * Returns a tag array for a given item array
1226 * @param array $item
1228 * @return array of tags
1229 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1231 private static function createTagList($item)
1235 $terms = Tag::getByURIId($item['uri-id'], [Tag::HASHTAG, Tag::MENTION, Tag::IMPLICIT_MENTION, Tag::EXCLUSIVE_MENTION]);
1236 foreach ($terms as $term) {
1237 if ($term['type'] == Tag::HASHTAG) {
1238 $url = DI::baseUrl() . '/search?tag=' . urlencode($term['name']);
1239 $tags[] = ['type' => 'Hashtag', 'href' => $url, 'name' => '#' . $term['name']];
1241 $contact = Contact::getByURL($term['url'], false, ['addr']);
1242 if (empty($contact)) {
1245 if (!empty($contact['addr'])) {
1246 $mention = '@' . $contact['addr'];
1248 $mention = '@' . $term['url'];
1251 $tags[] = ['type' => 'Mention', 'href' => $term['url'], 'name' => $mention];
1255 $announce = self::getAnnounceArray($item);
1256 // Mention the original author upon commented reshares
1257 if (!empty($announce['comment'])) {
1258 $tags[] = ['type' => 'Mention', 'href' => $announce['actor']['url'], 'name' => '@' . $announce['actor']['addr']];
1265 * Adds attachment data to the JSON document
1267 * @param array $item Data of the item that is to be posted
1268 * @param string $type Object type
1270 * @return array with attachment data
1271 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1273 private static function createAttachmentList($item, $type)
1277 $uriids = [$item['uri-id']];
1278 $shared = BBCode::fetchShareAttributes($item['body']);
1279 if (!empty($shared['guid'])) {
1280 $shared_item = Post::selectFirst(['uri-id'], ['guid' => $shared['guid']]);
1281 if (!empty($shared_item['uri-id'])) {
1282 $uriids[] = $shared_item['uri-id'];
1287 foreach ($uriids as $uriid) {
1288 foreach (Post\Media::getByURIId($uriid, [Post\Media::DOCUMENT, Post\Media::TORRENT]) as $attachment) {
1289 if (in_array($attachment['url'], $urls)) {
1292 $urls[] = $attachment['url'];
1294 $attach = ['type' => 'Document',
1295 'mediaType' => $attachment['mimetype'],
1296 'url' => $attachment['url'],
1297 'name' => $attachment['description']];
1299 if (!empty($attachment['height'])) {
1300 $attach['height'] = $attachment['height'];
1303 if (!empty($attachment['width'])) {
1304 $attach['width'] = $attachment['width'];
1307 if (!empty($attachment['preview'])) {
1308 $attach['image'] = $attachment['preview'];
1311 $attachments[] = $attach;
1315 if ($type != 'Note') {
1316 return $attachments;
1319 foreach ($uriids as $uriid) {
1320 foreach (Post\Media::getByURIId($uriid, [Post\Media::AUDIO, Post\Media::IMAGE, Post\Media::VIDEO]) as $attachment) {
1321 if (in_array($attachment['url'], $urls)) {
1324 $urls[] = $attachment['url'];
1326 $attach = ['type' => 'Document',
1327 'mediaType' => $attachment['mimetype'],
1328 'url' => $attachment['url'],
1329 'name' => $attachment['description']];
1331 if (!empty($attachment['height'])) {
1332 $attach['height'] = $attachment['height'];
1335 if (!empty($attachment['width'])) {
1336 $attach['width'] = $attachment['width'];
1339 if (!empty($attachment['preview'])) {
1340 $attach['image'] = $attachment['preview'];
1343 $attachments[] = $attach;
1345 // Currently deactivated, since it creates side effects on Mastodon and Pleroma.
1346 // It will be activated, once this cleared.
1348 foreach (Post\Media::getByURIId($uriid, [Post\Media::HTML]) as $attachment) {
1349 if (in_array($attachment['url'], $urls)) {
1352 $urls[] = $attachment['url'];
1354 $attachments[] = ['type' => 'Page',
1355 'mediaType' => $attachment['mimetype'],
1356 'url' => $attachment['url'],
1357 'name' => $attachment['description']];
1361 return $attachments;
1365 * Callback function to replace a Friendica style mention in a mention for a summary
1367 * @param array $match Matching values for the callback
1368 * @return string Replaced mention
1369 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1371 private static function mentionAddrCallback($match)
1373 if (empty($match[1])) {
1377 $data = Contact::getByURL($match[1], false, ['addr']);
1378 if (empty($data['addr'])) {
1382 return '@' . $data['addr'];
1386 * Remove image elements since they are added as attachment
1388 * @param string $body
1390 * @return string with removed images
1392 private static function removePictures($body)
1394 // Simplify image codes
1395 $body = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '[img]$3[/img]', $body);
1396 $body = preg_replace("/\[img\=(.*?)\](.*?)\[\/img\]/ism", '[img]$1[/img]', $body);
1398 // Now remove local links
1399 $body = preg_replace_callback(
1400 '/\[url=([^\[\]]*)\]\[img\](.*)\[\/img\]\[\/url\]/Usi',
1402 // We remove the link when it is a link to a local photo page
1403 if (Photo::isLocalPage($match[1])) {
1406 // otherwise we just return the link
1407 return '[url]' . $match[1] . '[/url]';
1412 // Remove all pictures
1413 $body = preg_replace("/\[img\]([^\[\]]*)\[\/img\]/Usi", '', $body);
1419 * Fetches the "context" value for a givem item array from the "conversation" table
1421 * @param array $item
1423 * @return string with context url
1424 * @throws \Exception
1426 private static function fetchContextURLForItem($item)
1428 $conversation = DBA::selectFirst('conversation', ['conversation-href', 'conversation-uri'], ['item-uri' => $item['parent-uri']]);
1429 if (DBA::isResult($conversation) && !empty($conversation['conversation-href'])) {
1430 $context_uri = $conversation['conversation-href'];
1431 } elseif (DBA::isResult($conversation) && !empty($conversation['conversation-uri'])) {
1432 $context_uri = $conversation['conversation-uri'];
1434 $context_uri = $item['parent-uri'] . '#context';
1436 return $context_uri;
1440 * Returns if the post contains sensitive content ("nsfw")
1442 * @param integer $uri_id
1445 * @throws \Exception
1447 private static function isSensitive($uri_id)
1449 return DBA::exists('tag-view', ['uri-id' => $uri_id, 'name' => 'nsfw']);
1453 * Creates event data
1455 * @param array $item
1457 * @return array with the event data
1458 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1460 private static function createEvent($item)
1463 $event['name'] = $item['event-summary'];
1464 $event['content'] = BBCode::convertForUriId($item['uri-id'], $item['event-desc'], BBCode::ACTIVITYPUB);
1465 $event['startTime'] = DateTimeFormat::utc($item['event-start'] . '+00:00', DateTimeFormat::ATOM);
1467 if (!$item['event-nofinish']) {
1468 $event['endTime'] = DateTimeFormat::utc($item['event-finish'] . '+00:00', DateTimeFormat::ATOM);
1471 if (!empty($item['event-location'])) {
1472 $item['location'] = $item['event-location'];
1473 $event['location'] = self::createLocation($item);
1476 $event['dfrn:adjust'] = (bool)$item['event-adjust'];
1482 * Creates a note/article object array
1484 * @param array $item
1486 * @return array with the object data
1487 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1488 * @throws \ImagickException
1490 public static function createNote($item)
1496 if ($item['event-type'] == 'event') {
1498 } elseif (!empty($item['title'])) {
1504 if ($item['deleted']) {
1505 $type = 'Tombstone';
1509 $data['id'] = $item['uri'];
1510 $data['type'] = $type;
1512 if ($item['deleted']) {
1516 $data['summary'] = BBCode::toPlaintext(BBCode::getAbstract($item['body'], Protocol::ACTIVITYPUB));
1518 if ($item['uri'] != $item['thr-parent']) {
1519 $data['inReplyTo'] = $item['thr-parent'];
1521 $data['inReplyTo'] = null;
1524 $data['diaspora:guid'] = $item['guid'];
1525 $data['published'] = DateTimeFormat::utc($item['created'] . '+00:00', DateTimeFormat::ATOM);
1527 if ($item['created'] != $item['edited']) {
1528 $data['updated'] = DateTimeFormat::utc($item['edited'] . '+00:00', DateTimeFormat::ATOM);
1531 $data['url'] = $item['plink'];
1532 $data['attributedTo'] = $item['author-link'];
1533 $data['sensitive'] = self::isSensitive($item['uri-id']);
1534 $data['context'] = self::fetchContextURLForItem($item);
1536 if (!empty($item['title'])) {
1537 $data['name'] = BBCode::toPlaintext($item['title'], false);
1540 $permission_block = self::createPermissionBlockForItem($item, false);
1542 $body = $item['body'];
1544 if ($type == 'Note') {
1545 $body = $item['raw-body'] ?? self::removePictures($body);
1549 * @todo Improve the automated summary
1550 * This part is currently deactivated. The automated summary seems to be more
1551 * confusing than helping. But possibly we will find a better way.
1552 * So the code is left here for now as a reminder
1554 * } elseif (($type == 'Article') && empty($data['summary'])) {
1555 * $regexp = "/[@!]\[url\=([^\[\]]*)\].*?\[\/url\]/ism";
1556 * $summary = preg_replace_callback($regexp, ['self', 'mentionAddrCallback'], $body);
1557 * $data['summary'] = BBCode::toPlaintext(Plaintext::shorten(self::removePictures($summary), 1000));
1561 if (empty($item['uid']) || !Feature::isEnabled($item['uid'], 'explicit_mentions')) {
1562 $body = self::prependMentions($body, $item['uri-id'], $item['author-link']);
1565 if ($type == 'Event') {
1566 $data = array_merge($data, self::createEvent($item));
1568 $body = BBCode::setMentionsToNicknames($body);
1570 $data['content'] = BBCode::convertForUriId($item['uri-id'], $body, BBCode::ACTIVITYPUB);
1573 // The regular "content" field does contain a minimized HTML. This is done since systems like
1574 // Mastodon has got problems with - for example - embedded pictures.
1575 // The contentMap does contain the unmodified HTML.
1576 $language = self::getLanguage($item);
1577 if (!empty($language)) {
1578 $richbody = BBCode::setMentionsToNicknames($item['body'] ?? '');
1579 $richbody = BBCode::removeAttachment($richbody);
1581 $data['contentMap'][$language] = BBCode::convertForUriId($item['uri-id'], $richbody, BBCode::EXTERNAL);
1584 $data['source'] = ['content' => $item['body'], 'mediaType' => "text/bbcode"];
1586 if (!empty($item['signed_text']) && ($item['uri'] != $item['thr-parent'])) {
1587 $data['diaspora:comment'] = $item['signed_text'];
1590 $data['attachment'] = self::createAttachmentList($item, $type);
1591 $data['tag'] = self::createTagList($item);
1593 if (empty($data['location']) && (!empty($item['coord']) || !empty($item['location']))) {
1594 $data['location'] = self::createLocation($item);
1597 if (!empty($item['app'])) {
1598 $data['generator'] = ['type' => 'Application', 'name' => $item['app']];
1601 $data = array_merge($data, $permission_block);
1607 * Fetches the language from the post, the user or the system.
1609 * @param array $item
1611 * @return string language string
1613 private static function getLanguage(array $item)
1615 // Try to fetch the language from the post itself
1616 if (!empty($item['language'])) {
1617 $languages = array_keys(json_decode($item['language'], true));
1618 if (!empty($languages[0])) {
1619 return $languages[0];
1623 // Otherwise use the user's language
1624 if (!empty($item['uid'])) {
1625 $user = DBA::selectFirst('user', ['language'], ['uid' => $item['uid']]);
1626 if (!empty($user['language'])) {
1627 return $user['language'];
1631 // And finally just use the system language
1632 return DI::config()->get('system', 'language');
1636 * Creates an an "add tag" entry
1638 * @param array $item
1639 * @param array $data activity data
1641 * @return array with activity data for adding tags
1642 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1643 * @throws \ImagickException
1645 private static function createAddTag($item, $data)
1647 $object = XML::parseString($item['object']);
1648 $target = XML::parseString($item["target"]);
1650 $data['diaspora:guid'] = $item['guid'];
1651 $data['actor'] = $item['author-link'];
1652 $data['target'] = (string)$target->id;
1653 $data['summary'] = BBCode::toPlaintext($item['body']);
1654 $data['object'] = ['id' => (string)$object->id, 'type' => 'tag', 'name' => (string)$object->title, 'content' => (string)$object->content];
1660 * Creates an announce object entry
1662 * @param array $item
1663 * @param array $data activity data
1665 * @return array with activity data
1666 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1667 * @throws \ImagickException
1669 private static function createAnnounce($item, $data)
1671 $orig_body = $item['body'];
1672 $announce = self::getAnnounceArray($item);
1673 if (empty($announce)) {
1674 $data['type'] = 'Create';
1675 $data['object'] = self::createNote($item);
1679 if (empty($announce['comment'])) {
1680 // Pure announce, without a quote
1681 $data['type'] = 'Announce';
1682 $data['object'] = $announce['object']['uri'];
1687 $data['type'] = 'Create';
1688 $item['body'] = $announce['comment'] . "\n" . $announce['object']['plink'];
1689 $data['object'] = self::createNote($item);
1691 /// @todo Finally descide how to implement this in AP. This is a possible way:
1692 $data['object']['attachment'][] = self::createNote($announce['object']);
1694 $data['object']['source']['content'] = $orig_body;
1699 * Return announce related data if the item is an annunce
1701 * @param array $item
1705 public static function getAnnounceArray($item)
1707 $reshared = Item::getShareArray($item);
1708 if (empty($reshared['guid'])) {
1712 $reshared_item = Post::selectFirst(Item::DELIVER_FIELDLIST, ['guid' => $reshared['guid']]);
1713 if (!DBA::isResult($reshared_item)) {
1717 if (!in_array($reshared_item['network'], [Protocol::ACTIVITYPUB, Protocol::DFRN])) {
1721 $profile = APContact::getByURL($reshared_item['author-link'], false);
1722 if (empty($profile)) {
1726 return ['object' => $reshared_item, 'actor' => $profile, 'comment' => $reshared['comment']];
1730 * Checks if the provided item array is an announce
1732 * @param array $item
1736 public static function isAnnounce($item)
1738 if (!empty($item['verb']) && ($item['verb'] == Activity::ANNOUNCE)) {
1742 $announce = self::getAnnounceArray($item);
1743 if (empty($announce)) {
1747 return empty($announce['comment']);
1751 * Creates an activity id for a given contact id
1753 * @param integer $cid Contact ID of target
1755 * @return bool|string activity id
1757 public static function activityIDFromContact($cid)
1759 $contact = DBA::selectFirst('contact', ['uid', 'id', 'created'], ['id' => $cid]);
1760 if (!DBA::isResult($contact)) {
1764 $hash = hash('ripemd128', $contact['uid'].'-'.$contact['id'].'-'.$contact['created']);
1765 $uuid = substr($hash, 0, 8). '-' . substr($hash, 8, 4) . '-' . substr($hash, 12, 4) . '-' . substr($hash, 16, 4) . '-' . substr($hash, 20, 12);
1766 return DI::baseUrl() . '/activity/' . $uuid;
1770 * Transmits a contact suggestion to a given inbox
1772 * @param integer $uid User ID
1773 * @param string $inbox Target inbox
1774 * @param integer $suggestion_id Suggestion ID
1776 * @return boolean was the transmission successful?
1777 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1779 public static function sendContactSuggestion($uid, $inbox, $suggestion_id)
1781 $owner = User::getOwnerDataById($uid);
1783 $suggestion = DI::fsuggest()->getById($suggestion_id);
1785 $data = ['@context' => ActivityPub::CONTEXT,
1786 'id' => DI::baseUrl() . '/activity/' . System::createGUID(),
1787 'type' => 'Announce',
1788 'actor' => $owner['url'],
1789 'object' => $suggestion->url,
1790 'content' => $suggestion->note,
1791 'instrument' => self::getService(),
1792 'to' => [ActivityPub::PUBLIC_COLLECTION],
1795 $signed = LDSignature::sign($data, $owner);
1797 Logger::log('Deliver profile deletion for user ' . $uid . ' to ' . $inbox . ' via ActivityPub', Logger::DEBUG);
1798 return HTTPSignature::transmit($signed, $inbox, $uid);
1802 * Transmits a profile relocation to a given inbox
1804 * @param integer $uid User ID
1805 * @param string $inbox Target inbox
1807 * @return boolean was the transmission successful?
1808 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1810 public static function sendProfileRelocation($uid, $inbox)
1812 $owner = User::getOwnerDataById($uid);
1814 $data = ['@context' => ActivityPub::CONTEXT,
1815 'id' => DI::baseUrl() . '/activity/' . System::createGUID(),
1816 'type' => 'dfrn:relocate',
1817 'actor' => $owner['url'],
1818 'object' => $owner['url'],
1819 'published' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
1820 'instrument' => self::getService(),
1821 'to' => [ActivityPub::PUBLIC_COLLECTION],
1824 $signed = LDSignature::sign($data, $owner);
1826 Logger::log('Deliver profile relocation for user ' . $uid . ' to ' . $inbox . ' via ActivityPub', Logger::DEBUG);
1827 return HTTPSignature::transmit($signed, $inbox, $uid);
1831 * Transmits a profile deletion to a given inbox
1833 * @param integer $uid User ID
1834 * @param string $inbox Target inbox
1836 * @return boolean was the transmission successful?
1837 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1839 public static function sendProfileDeletion($uid, $inbox)
1841 $owner = User::getOwnerDataById($uid);
1843 if (empty($owner)) {
1844 Logger::error('No owner data found, the deletion message cannot be processed.', ['user' => $uid]);
1848 if (empty($owner['uprvkey'])) {
1849 Logger::error('No private key for owner found, the deletion message cannot be processed.', ['user' => $uid]);
1853 $data = ['@context' => ActivityPub::CONTEXT,
1854 'id' => DI::baseUrl() . '/activity/' . System::createGUID(),
1856 'actor' => $owner['url'],
1857 'object' => $owner['url'],
1858 'published' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
1859 'instrument' => self::getService(),
1860 'to' => [ActivityPub::PUBLIC_COLLECTION],
1863 $signed = LDSignature::sign($data, $owner);
1865 Logger::log('Deliver profile deletion for user ' . $uid . ' to ' . $inbox . ' via ActivityPub', Logger::DEBUG);
1866 return HTTPSignature::transmit($signed, $inbox, $uid);
1870 * Transmits a profile change to a given inbox
1872 * @param integer $uid User ID
1873 * @param string $inbox Target inbox
1875 * @return boolean was the transmission successful?
1876 * @throws HTTPException\InternalServerErrorException
1877 * @throws HTTPException\NotFoundException
1878 * @throws \ImagickException
1880 public static function sendProfileUpdate(int $uid, string $inbox): bool
1882 $owner = User::getOwnerDataById($uid);
1883 $profile = APContact::getByURL($owner['url']);
1885 $data = ['@context' => ActivityPub::CONTEXT,
1886 'id' => DI::baseUrl() . '/activity/' . System::createGUID(),
1888 'actor' => $owner['url'],
1889 'object' => self::getProfile($uid),
1890 'published' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
1891 'instrument' => self::getService(),
1892 'to' => [$profile['followers']],
1895 $signed = LDSignature::sign($data, $owner);
1897 Logger::log('Deliver profile update for user ' . $uid . ' to ' . $inbox . ' via ActivityPub', Logger::DEBUG);
1898 return HTTPSignature::transmit($signed, $inbox, $uid);
1902 * Transmits a given activity to a target
1904 * @param string $activity Type name
1905 * @param string $target Target profile
1906 * @param integer $uid User ID
1908 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1909 * @throws \ImagickException
1910 * @throws \Exception
1912 public static function sendActivity($activity, $target, $uid, $id = '')
1914 $profile = APContact::getByURL($target);
1915 if (empty($profile['inbox'])) {
1916 Logger::warning('No inbox found for target', ['target' => $target, 'profile' => $profile]);
1920 $owner = User::getOwnerDataById($uid);
1923 $id = DI::baseUrl() . '/activity/' . System::createGUID();
1926 $data = ['@context' => ActivityPub::CONTEXT,
1928 'type' => $activity,
1929 'actor' => $owner['url'],
1930 'object' => $profile['url'],
1931 'instrument' => self::getService(),
1932 'to' => [$profile['url']]];
1934 Logger::log('Sending activity ' . $activity . ' to ' . $target . ' for user ' . $uid, Logger::DEBUG);
1936 $signed = LDSignature::sign($data, $owner);
1937 return HTTPSignature::transmit($signed, $profile['inbox'], $uid);
1941 * Transmits a "follow object" activity to a target
1942 * This is a preparation for sending automated "follow" requests when receiving "Announce" messages
1944 * @param string $object Object URL
1945 * @param string $target Target profile
1946 * @param integer $uid User ID
1948 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1949 * @throws \ImagickException
1950 * @throws \Exception
1952 public static function sendFollowObject($object, $target, $uid = 0)
1954 $profile = APContact::getByURL($target);
1955 if (empty($profile['inbox'])) {
1956 Logger::warning('No inbox found for target', ['target' => $target, 'profile' => $profile]);
1961 // Fetch the list of administrators
1962 $admin_mail = explode(',', str_replace(' ', '', DI::config()->get('config', 'admin_email')));
1964 // We need to use some user as a sender. It doesn't care who it will send. We will use an administrator account.
1965 $condition = ['verified' => true, 'blocked' => false, 'account_removed' => false, 'account_expired' => false, 'email' => $admin_mail];
1966 $first_user = DBA::selectFirst('user', ['uid'], $condition);
1967 $uid = $first_user['uid'];
1970 $condition = ['verb' => Activity::FOLLOW, 'uid' => 0, 'parent-uri' => $object,
1971 'author-id' => Contact::getPublicIdByUserId($uid)];
1972 if (Post::exists($condition)) {
1973 Logger::log('Follow for ' . $object . ' for user ' . $uid . ' does already exist.', Logger::DEBUG);
1977 $owner = User::getOwnerDataById($uid);
1979 $data = ['@context' => ActivityPub::CONTEXT,
1980 'id' => DI::baseUrl() . '/activity/' . System::createGUID(),
1982 'actor' => $owner['url'],
1983 'object' => $object,
1984 'instrument' => self::getService(),
1985 'to' => [$profile['url']]];
1987 Logger::log('Sending follow ' . $object . ' to ' . $target . ' for user ' . $uid, Logger::DEBUG);
1989 $signed = LDSignature::sign($data, $owner);
1990 return HTTPSignature::transmit($signed, $profile['inbox'], $uid);
1994 * Transmit a message that the contact request had been accepted
1996 * @param string $target Target profile
1998 * @param integer $uid User ID
1999 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2000 * @throws \ImagickException
2002 public static function sendContactAccept($target, $id, $uid)
2004 $profile = APContact::getByURL($target);
2005 if (empty($profile['inbox'])) {
2006 Logger::warning('No inbox found for target', ['target' => $target, 'profile' => $profile]);
2010 $owner = User::getOwnerDataById($uid);
2011 $data = ['@context' => ActivityPub::CONTEXT,
2012 'id' => DI::baseUrl() . '/activity/' . System::createGUID(),
2014 'actor' => $owner['url'],
2016 'id' => (string)$id,
2018 'actor' => $profile['url'],
2019 'object' => $owner['url']
2021 'instrument' => self::getService(),
2022 'to' => [$profile['url']]];
2024 Logger::debug('Sending accept to ' . $target . ' for user ' . $uid . ' with id ' . $id);
2026 $signed = LDSignature::sign($data, $owner);
2027 HTTPSignature::transmit($signed, $profile['inbox'], $uid);
2031 * Reject a contact request or terminates the contact relation
2033 * @param string $target Target profile
2035 * @param integer $uid User ID
2036 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2037 * @throws \ImagickException
2039 public static function sendContactReject($target, $id, $uid)
2041 $profile = APContact::getByURL($target);
2042 if (empty($profile['inbox'])) {
2043 Logger::warning('No inbox found for target', ['target' => $target, 'profile' => $profile]);
2047 $owner = User::getOwnerDataById($uid);
2048 $data = ['@context' => ActivityPub::CONTEXT,
2049 'id' => DI::baseUrl() . '/activity/' . System::createGUID(),
2051 'actor' => $owner['url'],
2053 'id' => (string)$id,
2055 'actor' => $profile['url'],
2056 'object' => $owner['url']
2058 'instrument' => self::getService(),
2059 'to' => [$profile['url']]];
2061 Logger::debug('Sending reject to ' . $target . ' for user ' . $uid . ' with id ' . $id);
2063 $signed = LDSignature::sign($data, $owner);
2064 HTTPSignature::transmit($signed, $profile['inbox'], $uid);
2068 * Transmits a message that we don't want to follow this contact anymore
2070 * @param string $target Target profile
2071 * @param integer $uid User ID
2072 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2073 * @throws \ImagickException
2074 * @throws \Exception
2075 * @return bool success
2077 public static function sendContactUndo($target, $cid, $uid)
2079 $profile = APContact::getByURL($target);
2080 if (empty($profile['inbox'])) {
2081 Logger::warning('No inbox found for target', ['target' => $target, 'profile' => $profile]);
2085 $object_id = self::activityIDFromContact($cid);
2086 if (empty($object_id)) {
2090 $id = DI::baseUrl() . '/activity/' . System::createGUID();
2092 $owner = User::getOwnerDataById($uid);
2093 $data = ['@context' => ActivityPub::CONTEXT,
2096 'actor' => $owner['url'],
2097 'object' => ['id' => $object_id, 'type' => 'Follow',
2098 'actor' => $owner['url'],
2099 'object' => $profile['url']],
2100 'instrument' => self::getService(),
2101 'to' => [$profile['url']]];
2103 Logger::log('Sending undo to ' . $target . ' for user ' . $uid . ' with id ' . $id, Logger::DEBUG);
2105 $signed = LDSignature::sign($data, $owner);
2106 return HTTPSignature::transmit($signed, $profile['inbox'], $uid);
2109 private static function prependMentions($body, int $uriid, string $authorLink)
2113 foreach (Tag::getByURIId($uriid, [Tag::IMPLICIT_MENTION]) as $tag) {
2114 $profile = Contact::getByURL($tag['url'], false, ['addr', 'contact-type', 'nick']);
2115 if (!empty($profile['addr'])
2116 && $profile['contact-type'] != Contact::TYPE_COMMUNITY
2117 && !strstr($body, $profile['addr'])
2118 && !strstr($body, $tag['url'])
2119 && $tag['url'] !== $authorLink
2121 $mentions[] = '@[url=' . $tag['url'] . ']' . $profile['nick'] . '[/url]';
2125 $mentions[] = $body;
2127 return implode(' ', $mentions);