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\Content\Text\Plaintext;
27 use Friendica\Core\Cache\Duration;
28 use Friendica\Core\Logger;
29 use Friendica\Core\Protocol;
30 use Friendica\Core\System;
31 use Friendica\Database\DBA;
33 use Friendica\Model\APContact;
34 use Friendica\Model\Contact;
35 use Friendica\Model\Conversation;
36 use Friendica\Model\GServer;
37 use Friendica\Model\Item;
38 use Friendica\Model\ItemURI;
39 use Friendica\Model\Profile;
40 use Friendica\Model\Photo;
41 use Friendica\Model\Post;
42 use Friendica\Model\Tag;
43 use Friendica\Model\User;
44 use Friendica\Protocol\Activity;
45 use Friendica\Protocol\ActivityPub;
46 use Friendica\Protocol\Relay;
47 use Friendica\Util\DateTimeFormat;
48 use Friendica\Util\HTTPSignature;
49 use Friendica\Util\JsonLD;
50 use Friendica\Util\LDSignature;
51 use Friendica\Util\Map;
52 use Friendica\Util\Network;
53 use Friendica\Util\XML;
56 * ActivityPub Transmitter Protocol class
64 * Add relay servers to the list of inboxes
66 * @param array $inboxes
67 * @return array inboxes with added relay servers
69 public static function addRelayServerInboxes(array $inboxes = [])
71 $contacts = DBA::select('apcontact', ['inbox'],
72 ["`type` = ? AND `url` IN (SELECT `url` FROM `contact` WHERE `uid` = ? AND `rel` = ?)",
73 'Application', 0, Contact::FRIEND]);
74 while ($contact = DBA::fetch($contacts)) {
75 $inboxes[$contact['inbox']] = $contact['inbox'];
77 DBA::close($contacts);
83 * Add relay servers to the list of inboxes
85 * @param array $inboxes
86 * @return array inboxes with added relay servers
88 public static function addRelayServerInboxesForItem(int $item_id, array $inboxes = [])
90 $item = Post::selectFirst(['uid'], ['id' => $item_id]);
95 $relays = Relay::getList($item_id, [], [Protocol::ACTIVITYPUB]);
100 foreach ($relays as $relay) {
101 $contact = Contact::getByURLForUser($relay['url'], $item['uid'], false, ['id']);
102 $inboxes[$relay['batch']][] = $contact['id'] ?? 0;
108 * Subscribe to a relay
110 * @param string $url Subscribe actor url
111 * @return bool success
113 public static function sendRelayFollow(string $url)
115 $contact = Contact::getByURL($url);
116 if (empty($contact)) {
120 $activity_id = ActivityPub\Transmitter::activityIDFromContact($contact['id']);
121 $success = ActivityPub\Transmitter::sendActivity('Follow', $url, 0, $activity_id);
123 DBA::update('contact', ['rel' => Contact::FRIEND], ['id' => $contact['id']]);
130 * Unsubscribe from a relay
132 * @param string $url Subscribe actor url
133 * @param bool $force Set the relay status as non follower even if unsubscribe hadn't worked
134 * @return bool success
136 public static function sendRelayUndoFollow(string $url, bool $force = false)
138 $contact = Contact::getByURL($url);
139 if (empty($contact)) {
143 $success = self::sendContactUndo($url, $contact['id'], 0);
144 if ($success || $force) {
145 DBA::update('contact', ['rel' => Contact::NOTHING], ['id' => $contact['id']]);
152 * Collects a list of contacts of the given owner
154 * @param array $owner Owner array
155 * @param int|array $rel The relevant value(s) contact.rel should match
156 * @param string $module The name of the relevant AP endpoint module (followers|following)
157 * @param integer $page Page number
159 * @return array of owners
162 public static function getContacts($owner, $rel, $module, $page = null)
166 'uid' => $owner['uid'],
174 $condition = DBA::buildCondition($parameters);
176 $sql = "SELECT COUNT(*) as `count`
178 JOIN `apcontact` ON `apcontact`.`url` = `contact`.`url`
181 $contacts = DBA::fetchFirst($sql, ...$parameters);
183 $modulePath = '/' . $module . '/';
185 $data = ['@context' => ActivityPub::CONTEXT];
186 $data['id'] = DI::baseUrl() . $modulePath . $owner['nickname'];
187 $data['type'] = 'OrderedCollection';
188 $data['totalItems'] = $contacts['count'];
190 // When we hide our friends we will only show the pure number but don't allow more.
191 $profile = Profile::getByUID($owner['uid']);
192 if (!empty($profile['hide-friends'])) {
197 $data['first'] = DI::baseUrl() . $modulePath . $owner['nickname'] . '?page=1';
199 $data['type'] = 'OrderedCollectionPage';
202 $sql = "SELECT `contact`.`url`
204 JOIN `apcontact` ON `apcontact`.`url` = `contact`.`url`
208 $parameters[] = ($page - 1) * 100;
211 $contacts = DBA::p($sql, ...$parameters);
212 while ($contact = DBA::fetch($contacts)) {
213 $list[] = $contact['url'];
215 DBA::close($contacts);
218 $data['next'] = DI::baseUrl() . $modulePath . $owner['nickname'] . '?page=' . ($page + 1);
221 $data['partOf'] = DI::baseUrl() . $modulePath . $owner['nickname'];
223 $data['orderedItems'] = $list;
230 * Public posts for the given owner
232 * @param array $owner Owner array
233 * @param integer $page Page number
234 * @param string $requester URL of requesting account
236 * @return array of posts
237 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
238 * @throws \ImagickException
240 public static function getOutbox($owner, $page = null, $requester = '')
242 $public_contact = Contact::getIdForURL($owner['url']);
243 $condition = ['uid' => 0, 'contact-id' => $public_contact,
244 'private' => [Item::PUBLIC, Item::UNLISTED]];
246 if (!empty($requester)) {
247 $requester_id = Contact::getIdForURL($requester, $owner['uid']);
248 if (!empty($requester_id)) {
249 $permissionSets = DI::permissionSet()->selectByContactId($requester_id, $owner['uid']);
250 if (!empty($permissionSets)) {
251 $condition = ['uid' => $owner['uid'], 'origin' => true,
252 'psid' => array_merge($permissionSets->column('id'),
253 [DI::permissionSet()->getIdFromACL($owner['uid'], '', '', '', '')])];
258 $condition = array_merge($condition,
259 ['author-id' => $public_contact,
260 'gravity' => [GRAVITY_PARENT, GRAVITY_COMMENT],
261 'deleted' => false, 'visible' => true]);
263 $count = Post::count($condition);
265 $data = ['@context' => ActivityPub::CONTEXT];
266 $data['id'] = DI::baseUrl() . '/outbox/' . $owner['nickname'];
267 $data['type'] = 'OrderedCollection';
268 $data['totalItems'] = $count;
271 $data['first'] = DI::baseUrl() . '/outbox/' . $owner['nickname'] . '?page=1';
273 $data['type'] = 'OrderedCollectionPage';
276 $condition['parent-network'] = Protocol::NATIVE_SUPPORT;
278 $items = Post::select(['id'], $condition, ['limit' => [($page - 1) * 20, 20], 'order' => ['created' => true]]);
279 while ($item = Post::fetch($items)) {
280 $activity = self::createActivityFromItem($item['id'], true);
281 $activity['type'] = $activity['type'] == 'Update' ? 'Create' : $activity['type'];
283 // Only list "Create" activity objects here, no reshares
284 if (!empty($activity['object']) && ($activity['type'] == 'Create')) {
285 $list[] = $activity['object'];
291 $data['next'] = DI::baseUrl() . '/outbox/' . $owner['nickname'] . '?page=' . ($page + 1);
294 $data['partOf'] = DI::baseUrl() . '/outbox/' . $owner['nickname'];
296 $data['orderedItems'] = $list;
303 * Return the service array containing information the used software and it's url
305 * @return array with service data
307 private static function getService()
309 return ['type' => 'Service',
310 'name' => FRIENDICA_PLATFORM . " '" . FRIENDICA_CODENAME . "' " . FRIENDICA_VERSION . '-' . DB_UPDATE_VERSION,
311 'url' => DI::baseUrl()->get()];
315 * Return the ActivityPub profile of the given user
317 * @param integer $uid User ID
318 * @return array with profile data
319 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
321 public static function getProfile($uid)
324 $condition = ['uid' => $uid, 'blocked' => false, 'account_expired' => false,
325 'account_removed' => false, 'verified' => true];
326 $fields = ['guid', 'nickname', 'pubkey', 'account-type', 'page-flags'];
327 $user = DBA::selectFirst('user', $fields, $condition);
328 if (!DBA::isResult($user)) {
332 $fields = ['locality', 'region', 'country-name'];
333 $profile = DBA::selectFirst('profile', $fields, ['uid' => $uid]);
334 if (!DBA::isResult($profile)) {
338 $fields = ['name', 'url', 'location', 'about', 'avatar', 'photo'];
339 $contact = DBA::selectFirst('contact', $fields, ['uid' => $uid, 'self' => true]);
340 if (!DBA::isResult($contact)) {
344 $contact = User::getSystemAccount();
345 $user = ['guid' => '', 'nickname' => $contact['nick'], 'pubkey' => $contact['pubkey'],
346 'account-type' => $contact['contact-type'], 'page-flags' => User::PAGE_FLAGS_NORMAL];
347 $profile = ['locality' => '', 'region' => '', 'country-name' => ''];
350 $data = ['@context' => ActivityPub::CONTEXT];
351 $data['id'] = $contact['url'];
353 if (!empty($user['guid'])) {
354 $data['diaspora:guid'] = $user['guid'];
357 $data['type'] = ActivityPub::ACCOUNT_TYPES[$user['account-type']];
360 $data['following'] = DI::baseUrl() . '/following/' . $user['nickname'];
361 $data['followers'] = DI::baseUrl() . '/followers/' . $user['nickname'];
362 $data['inbox'] = DI::baseUrl() . '/inbox/' . $user['nickname'];
363 $data['outbox'] = DI::baseUrl() . '/outbox/' . $user['nickname'];
365 $data['inbox'] = DI::baseUrl() . '/friendica/inbox';
368 $data['preferredUsername'] = $user['nickname'];
369 $data['name'] = $contact['name'];
371 if (!empty($profile['country-name'] . $profile['region'] . $profile['locality'])) {
372 $data['vcard:hasAddress'] = ['@type' => 'vcard:Home', 'vcard:country-name' => $profile['country-name'],
373 'vcard:region' => $profile['region'], 'vcard:locality' => $profile['locality']];
376 if (!empty($contact['about'])) {
377 $data['summary'] = BBCode::convert($contact['about'], false);
380 $data['url'] = $contact['url'];
381 $data['manuallyApprovesFollowers'] = in_array($user['page-flags'], [User::PAGE_FLAGS_NORMAL, User::PAGE_FLAGS_PRVGROUP]);
382 $data['publicKey'] = ['id' => $contact['url'] . '#main-key',
383 'owner' => $contact['url'],
384 'publicKeyPem' => $user['pubkey']];
385 $data['endpoints'] = ['sharedInbox' => DI::baseUrl() . '/inbox'];
386 $data['icon'] = ['type' => 'Image',
387 'url' => $contact['photo']];
389 $data['generator'] = self::getService();
391 // tags: https://kitty.town/@inmysocks/100656097926961126.json
396 * @param string $username
398 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
400 public static function getDeletedUser($username)
403 '@context' => ActivityPub::CONTEXT,
404 'id' => DI::baseUrl() . '/profile/' . $username,
405 'type' => 'Tombstone',
406 'published' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
407 'updated' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
408 'deleted' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
413 * Returns an array with permissions of a given item array
417 * @return array with permissions
418 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
419 * @throws \ImagickException
421 private static function fetchPermissionBlockFromConversation($item)
423 if (empty($item['thr-parent'])) {
427 $condition = ['item-uri' => $item['thr-parent'], 'protocol' => Conversation::PARCEL_ACTIVITYPUB];
428 $conversation = DBA::selectFirst('conversation', ['source'], $condition);
429 if (!DBA::isResult($conversation)) {
433 $activity = json_decode($conversation['source'], true);
435 $actor = JsonLD::fetchElement($activity, 'actor', 'id');
436 if (!empty($actor)) {
437 $permissions['to'][] = $actor;
438 $profile = APContact::getByURL($actor);
443 $item_profile = APContact::getByURL($item['author-link']);
444 $exclude[] = $item['author-link'];
446 if ($item['gravity'] == GRAVITY_PARENT) {
447 $exclude[] = $item['owner-link'];
450 foreach (['to', 'cc', 'bto', 'bcc'] as $element) {
451 if (empty($activity[$element])) {
454 if (is_string($activity[$element])) {
455 $activity[$element] = [$activity[$element]];
458 foreach ($activity[$element] as $receiver) {
459 if (empty($receiver)) {
463 if (!empty($profile['followers']) && $receiver == $profile['followers'] && !empty($item_profile['followers'])) {
464 $permissions[$element][] = $item_profile['followers'];
465 } elseif (!in_array($receiver, $exclude)) {
466 $permissions[$element][] = $receiver;
474 * Check if the given item id is from ActivityPub
476 * @param integer $item_id
477 * @return boolean "true" if the post is from ActivityPub
479 private static function isAPPost(int $item_id)
481 if (empty($item_id)) {
485 return Post::exists(['id' => $item_id, 'network' => Protocol::ACTIVITYPUB]);
489 * Creates an array of permissions from an item thread
491 * @param array $item Item array
492 * @param boolean $blindcopy addressing via "bcc" or "cc"?
493 * @param integer $last_id Last item id for adding receivers
494 * @param boolean $forum_mode "true" means that we are sending content to a forum
496 * @return array with permission data
497 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
498 * @throws \ImagickException
500 private static function createPermissionBlockForItem($item, $blindcopy, $last_id = 0, $forum_mode = false)
503 $last_id = $item['id'];
508 // Check if we should always deliver our stuff via BCC
509 if (!empty($item['uid'])) {
510 $profile = User::getOwnerDataById($item['uid']);
511 if (!empty($profile)) {
512 $always_bcc = $profile['hide-friends'];
516 if (DI::config()->get('system', 'ap_always_bcc')) {
520 if (self::isAnnounce($item) || DI::config()->get('debug', 'total_ap_delivery') || self::isAPPost($last_id)) {
521 // Will be activated in a later step
522 $networks = Protocol::FEDERATED;
524 // For now only send to these contacts:
525 $networks = [Protocol::ACTIVITYPUB, Protocol::OSTATUS];
528 $data = ['to' => [], 'cc' => [], 'bcc' => []];
530 if ($item['gravity'] == GRAVITY_PARENT) {
531 $actor_profile = APContact::getByURL($item['owner-link']);
533 $actor_profile = APContact::getByURL($item['author-link']);
536 $terms = Tag::getByURIId($item['uri-id'], [Tag::MENTION, Tag::IMPLICIT_MENTION, Tag::EXCLUSIVE_MENTION]);
538 if ($item['private'] != Item::PRIVATE) {
539 // Directly mention the original author upon a quoted reshare.
540 // Else just ensure that the original author receives the reshare.
541 $announce = self::getAnnounceArray($item);
542 if (!empty($announce['comment'])) {
543 $data['to'][] = $announce['actor']['url'];
544 } elseif (!empty($announce)) {
545 $data['cc'][] = $announce['actor']['url'];
548 $data = array_merge($data, self::fetchPermissionBlockFromConversation($item));
550 // Check if the item is completely public or unlisted
551 if ($item['private'] == Item::PUBLIC) {
552 $data['to'][] = ActivityPub::PUBLIC_COLLECTION;
554 $data['cc'][] = ActivityPub::PUBLIC_COLLECTION;
557 foreach ($terms as $term) {
558 $profile = APContact::getByURL($term['url'], false);
559 if (!empty($profile)) {
560 $data['to'][] = $profile['url'];
564 $receiver_list = Item::enumeratePermissions($item, true);
566 foreach ($terms as $term) {
567 $cid = Contact::getIdForURL($term['url'], $item['uid']);
568 if (!empty($cid) && in_array($cid, $receiver_list)) {
569 $contact = DBA::selectFirst('contact', ['url', 'network', 'protocol', 'gsid'], ['id' => $cid, 'network' => Protocol::FEDERATED]);
570 if (!DBA::isResult($contact) || !self::isAPContact($contact, $networks)) {
574 if (!empty($profile = APContact::getByURL($contact['url'], false))) {
575 $data['to'][] = $profile['url'];
580 foreach ($receiver_list as $receiver) {
581 $contact = DBA::selectFirst('contact', ['url', 'hidden', 'network', 'protocol', 'gsid'], ['id' => $receiver, 'network' => Protocol::FEDERATED]);
582 if (!DBA::isResult($contact) || !self::isAPContact($contact, $networks)) {
586 if (!empty($profile = APContact::getByURL($contact['url'], false))) {
587 if ($contact['hidden'] || $always_bcc) {
588 $data['bcc'][] = $profile['url'];
590 $data['cc'][] = $profile['url'];
596 if (!empty($item['parent'])) {
597 $parents = Post::select(['id', 'author-link', 'owner-link', 'gravity', 'uri'], ['parent' => $item['parent']]);
598 while ($parent = Post::fetch($parents)) {
599 if ($parent['gravity'] == GRAVITY_PARENT) {
600 $profile = APContact::getByURL($parent['owner-link'], false);
601 if (!empty($profile)) {
602 if ($item['gravity'] != GRAVITY_PARENT) {
603 // Comments to forums are directed to the forum
604 // But comments to forums aren't directed to the followers collection
605 // This rule is only valid when the actor isn't the forum.
606 // The forum needs to transmit their content to their followers.
607 if (($profile['type'] == 'Group') && ($profile['url'] != $actor_profile['url'])) {
608 $data['to'][] = $profile['url'];
610 $data['cc'][] = $profile['url'];
611 if (($item['private'] != Item::PRIVATE) && !empty($actor_profile['followers'])) {
612 $data['cc'][] = $actor_profile['followers'];
616 // Public thread parent post always are directed to the followers
617 if (($item['private'] != Item::PRIVATE) && !$forum_mode) {
618 $data['cc'][] = $actor_profile['followers'];
624 // Don't include data from future posts
625 if ($parent['id'] >= $last_id) {
629 $profile = APContact::getByURL($parent['author-link'], false);
630 if (!empty($profile)) {
631 if (($profile['type'] == 'Group') || ($parent['uri'] == $item['thr-parent'])) {
632 $data['to'][] = $profile['url'];
634 $data['cc'][] = $profile['url'];
638 DBA::close($parents);
641 $data['to'] = array_unique($data['to']);
642 $data['cc'] = array_unique($data['cc']);
643 $data['bcc'] = array_unique($data['bcc']);
645 if (($key = array_search($item['author-link'], $data['to'])) !== false) {
646 unset($data['to'][$key]);
649 if (($key = array_search($item['author-link'], $data['cc'])) !== false) {
650 unset($data['cc'][$key]);
653 if (($key = array_search($item['author-link'], $data['bcc'])) !== false) {
654 unset($data['bcc'][$key]);
657 foreach ($data['to'] as $to) {
658 if (($key = array_search($to, $data['cc'])) !== false) {
659 unset($data['cc'][$key]);
662 if (($key = array_search($to, $data['bcc'])) !== false) {
663 unset($data['bcc'][$key]);
667 foreach ($data['cc'] as $cc) {
668 if (($key = array_search($cc, $data['bcc'])) !== false) {
669 unset($data['bcc'][$key]);
673 $receivers = ['to' => array_values($data['to']), 'cc' => array_values($data['cc']), 'bcc' => array_values($data['bcc'])];
676 unset($receivers['bcc']);
683 * Check if an inbox is archived
685 * @param string $url Inbox url
687 * @return boolean "true" if inbox is archived
689 public static function archivedInbox($url)
691 return DBA::exists('inbox-status', ['url' => $url, 'archive' => true]);
695 * Check if a given contact should be delivered via AP
697 * @param array $contact
698 * @param array $networks
702 private static function isAPContact(array $contact, array $networks)
704 if (in_array($contact['network'], $networks) || ($contact['protocol'] == Protocol::ACTIVITYPUB)) {
708 return GServer::getProtocol($contact['gsid'] ?? 0) == Post\DeliveryData::ACTIVITYPUB;
712 * Fetches a list of inboxes of followers of a given user
714 * @param integer $uid User ID
715 * @param boolean $personal fetch personal inboxes
716 * @param boolean $all_ap Retrieve all AP enabled inboxes
718 * @return array of follower inboxes
719 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
720 * @throws \ImagickException
722 public static function fetchTargetInboxesforUser($uid, $personal = false, bool $all_ap = false)
728 if (!empty($item['uid'])) {
729 $profile = User::getOwnerDataById($item['uid']);
730 if (!empty($profile)) {
731 $isforum = $profile['account-type'] == User::ACCOUNT_TYPE_COMMUNITY;
735 if (DI::config()->get('debug', 'total_ap_delivery') || $all_ap) {
736 // Will be activated in a later step
737 $networks = Protocol::FEDERATED;
739 // For now only send to these contacts:
740 $networks = [Protocol::ACTIVITYPUB, Protocol::OSTATUS];
743 $condition = ['uid' => $uid, 'archive' => false, 'pending' => false, 'blocked' => false, 'network' => Protocol::FEDERATED];
746 $condition['rel'] = [Contact::FOLLOWER, Contact::FRIEND];
749 $contacts = DBA::select('contact', ['id', 'url', 'network', 'protocol', 'gsid'], $condition);
750 while ($contact = DBA::fetch($contacts)) {
751 if (Contact::isLocal($contact['url'])) {
755 if (!self::isAPContact($contact, $networks)) {
759 if ($isforum && ($contact['network'] == Protocol::DFRN)) {
763 if (Network::isUrlBlocked($contact['url'])) {
767 $profile = APContact::getByURL($contact['url'], false);
768 if (!empty($profile)) {
769 if (empty($profile['sharedinbox']) || $personal) {
770 $target = $profile['inbox'];
772 $target = $profile['sharedinbox'];
774 if (!self::archivedInbox($target)) {
775 $inboxes[$target][] = $contact['id'];
779 DBA::close($contacts);
785 * Fetches an array of inboxes for the given item and user
787 * @param array $item Item array
788 * @param integer $uid User ID
789 * @param boolean $personal fetch personal inboxes
790 * @param integer $last_id Last item id for adding receivers
791 * @param boolean $forum_mode "true" means that we are sending content to a forum
792 * @return array with inboxes
793 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
794 * @throws \ImagickException
796 public static function fetchTargetInboxes($item, $uid, $personal = false, $last_id = 0, $forum_mode = false)
798 $permissions = self::createPermissionBlockForItem($item, true, $last_id, $forum_mode);
799 if (empty($permissions)) {
805 if ($item['gravity'] == GRAVITY_ACTIVITY) {
806 $item_profile = APContact::getByURL($item['author-link'], false);
808 $item_profile = APContact::getByURL($item['owner-link'], false);
811 if (empty($item_profile)) {
815 $profile_uid = User::getIdForURL($item_profile['url']);
817 foreach (['to', 'cc', 'bto', 'bcc'] as $element) {
818 if (empty($permissions[$element])) {
822 $blindcopy = in_array($element, ['bto', 'bcc']);
824 foreach ($permissions[$element] as $receiver) {
825 if (empty($receiver) || Network::isUrlBlocked($receiver)) {
829 if ($item_profile && ($receiver == $item_profile['followers']) && ($uid == $profile_uid)) {
830 $inboxes = array_merge($inboxes, self::fetchTargetInboxesforUser($uid, $personal, self::isAPPost($last_id)));
832 if (Contact::isLocal($receiver)) {
836 $profile = APContact::getByURL($receiver, false);
837 if (!empty($profile)) {
838 $contact = Contact::getByURLForUser($receiver, $uid, false, ['id']);
840 if (empty($profile['sharedinbox']) || $personal || $blindcopy) {
841 $target = $profile['inbox'];
843 $target = $profile['sharedinbox'];
845 if (!self::archivedInbox($target)) {
846 $inboxes[$target][] = $contact['id'] ?? 0;
857 * Creates an array in the structure of the item table for a given mail id
859 * @param integer $mail_id
864 public static function ItemArrayFromMail($mail_id, $use_title = false)
866 $mail = DBA::selectFirst('mail', [], ['id' => $mail_id]);
867 if (!DBA::isResult($mail)) {
871 $reply = DBA::selectFirst('mail', ['uri', 'uri-id', 'from-url'], ['parent-uri' => $mail['parent-uri'], 'reply' => false]);
873 // Making the post more compatible for Mastodon by:
874 // - Making it a note and not an article (no title)
875 // - Moving the title into the "summary" field that is used as a "content warning"
878 $mail['body'] = '[abstract]' . $mail['title'] . "[/abstract]\n" . $mail['body'];
882 $mail['author-link'] = $mail['owner-link'] = $mail['from-url'];
883 $mail['owner-id'] = $mail['author-id'];
884 $mail['allow_cid'] = '<'.$mail['contact-id'].'>';
885 $mail['allow_gid'] = '';
886 $mail['deny_cid'] = '';
887 $mail['deny_gid'] = '';
888 $mail['private'] = Item::PRIVATE;
889 $mail['deleted'] = false;
890 $mail['edited'] = $mail['created'];
891 $mail['plink'] = DI::baseUrl() . '/message/' . $mail['id'];
892 $mail['parent-uri'] = $reply['uri'];
893 $mail['parent-uri-id'] = $reply['uri-id'];
894 $mail['parent-author-id'] = Contact::getIdForURL($reply['from-url'], 0, false);
895 $mail['gravity'] = ($mail['reply'] ? GRAVITY_COMMENT: GRAVITY_PARENT);
896 $mail['event-type'] = '';
897 $mail['language'] = '';
904 * Creates an activity array for a given mail id
906 * @param integer $mail_id
907 * @param boolean $object_mode Is the activity item is used inside another object?
909 * @return array of activity
912 public static function createActivityFromMail($mail_id, $object_mode = false)
914 $mail = self::ItemArrayFromMail($mail_id);
918 $object = self::createNote($mail);
921 $data = ['@context' => ActivityPub::CONTEXT];
926 $data['id'] = $mail['uri'] . '/Create';
927 $data['type'] = 'Create';
928 $data['actor'] = $mail['author-link'];
929 $data['published'] = DateTimeFormat::utc($mail['created'] . '+00:00', DateTimeFormat::ATOM);
930 $data['instrument'] = self::getService();
931 $data = array_merge($data, self::createPermissionBlockForItem($mail, true));
933 if (empty($data['to']) && !empty($data['cc'])) {
934 $data['to'] = $data['cc'];
937 if (empty($data['to']) && !empty($data['bcc'])) {
938 $data['to'] = $data['bcc'];
944 $object['to'] = $data['to'];
945 $object['tag'] = [['type' => 'Mention', 'href' => $object['to'][0], 'name' => '']];
947 unset($object['cc']);
948 unset($object['bcc']);
950 $data['directMessage'] = true;
952 $data['object'] = $object;
954 $owner = User::getOwnerDataById($mail['uid']);
956 if (!$object_mode && !empty($owner)) {
957 return LDSignature::sign($data, $owner);
964 * Returns the activity type of a given item
968 * @return string with activity type
969 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
970 * @throws \ImagickException
972 private static function getTypeOfItem($item)
976 // Only check for a reshare, if it is a real reshare and no quoted reshare
977 if (strpos($item['body'], "[share") === 0) {
978 $announce = self::getAnnounceArray($item);
979 $reshared = !empty($announce);
984 } elseif ($item['verb'] == Activity::POST) {
985 if ($item['created'] == $item['edited']) {
990 } elseif ($item['verb'] == Activity::LIKE) {
992 } elseif ($item['verb'] == Activity::DISLIKE) {
994 } elseif ($item['verb'] == Activity::ATTEND) {
996 } elseif ($item['verb'] == Activity::ATTENDNO) {
998 } elseif ($item['verb'] == Activity::ATTENDMAYBE) {
999 $type = 'TentativeAccept';
1000 } elseif ($item['verb'] == Activity::FOLLOW) {
1002 } elseif ($item['verb'] == Activity::TAG) {
1004 } elseif ($item['verb'] == Activity::ANNOUNCE) {
1014 * Creates the activity or fetches it from the cache
1016 * @param integer $item_id
1017 * @param boolean $force Force new cache entry
1019 * @return array with the activity
1020 * @throws \Exception
1022 public static function createCachedActivityFromItem($item_id, $force = false)
1024 $cachekey = 'APDelivery:createActivity:' . $item_id;
1027 $data = DI::cache()->get($cachekey);
1028 if (!is_null($data)) {
1033 $data = self::createActivityFromItem($item_id);
1035 DI::cache()->set($cachekey, $data, Duration::QUARTER_HOUR);
1040 * Creates an activity array for a given item id
1042 * @param integer $item_id
1043 * @param boolean $object_mode Is the activity item is used inside another object?
1045 * @return false|array
1046 * @throws \Exception
1048 public static function createActivityFromItem(int $item_id, bool $object_mode = false)
1050 Logger::info('Fetching activity', ['item' => $item_id]);
1051 $item = Post::selectFirst(Item::DELIVER_FIELDLIST, ['id' => $item_id, 'parent-network' => Protocol::NATIVE_SUPPORT]);
1052 if (!DBA::isResult($item)) {
1056 // In case of a forum post ensure to return the original post if author and forum are on the same machine
1057 if (($item['gravity'] == GRAVITY_PARENT) && !empty($item['forum_mode'])) {
1058 $author = Contact::getById($item['author-id'], ['nurl']);
1059 if (!empty($author['nurl'])) {
1060 $self = Contact::selectFirst(['uid'], ['nurl' => $author['nurl'], 'self' => true]);
1061 if (!empty($self['uid'])) {
1062 $forum_item = Post::selectFirst(Item::DELIVER_FIELDLIST, ['uri-id' => $item['uri-id'], 'uid' => $self['uid']]);
1063 if (DBA::isResult($forum_item)) {
1064 $item = $forum_item;
1070 if (empty($item['uri-id'])) {
1071 Logger::warning('Item without uri-id', ['item' => $item]);
1075 if (!$item['deleted']) {
1076 $condition = ['item-uri' => $item['uri'], 'protocol' => Conversation::PARCEL_ACTIVITYPUB];
1077 $conversation = DBA::selectFirst('conversation', ['source'], $condition);
1078 if (!$item['origin'] && DBA::isResult($conversation)) {
1079 $data = json_decode($conversation['source'], true);
1080 if (!empty($data['type'])) {
1081 if (in_array($data['type'], ['Create', 'Update'])) {
1083 unset($data['@context']);
1084 unset($data['signature']);
1086 Logger::info('Return stored conversation', ['item' => $item_id]);
1088 } elseif (in_array('as:' . $data['type'], Receiver::CONTENT_TYPES)) {
1089 if (!empty($data['@context'])) {
1090 $context = $data['@context'];
1091 unset($data['@context']);
1093 unset($data['actor']);
1100 $type = self::getTypeOfItem($item);
1102 if (!$object_mode) {
1103 $data = ['@context' => $context ?? ActivityPub::CONTEXT];
1105 if ($item['deleted'] && ($item['gravity'] == GRAVITY_ACTIVITY)) {
1107 } elseif ($item['deleted']) {
1114 if ($type == 'Delete') {
1115 $data['id'] = Item::newURI($item['uid'], $item['guid']) . '/' . $type;;
1116 } elseif (($item['gravity'] == GRAVITY_ACTIVITY) && ($type != 'Undo')) {
1117 $data['id'] = $item['uri'];
1119 $data['id'] = $item['uri'] . '/' . $type;
1122 $data['type'] = $type;
1124 if (($type != 'Announce') || ($item['gravity'] != GRAVITY_PARENT)) {
1125 $data['actor'] = $item['author-link'];
1127 $data['actor'] = $item['owner-link'];
1130 $data['published'] = DateTimeFormat::utc($item['created'] . '+00:00', DateTimeFormat::ATOM);
1132 $data['instrument'] = self::getService();
1134 $data = array_merge($data, self::createPermissionBlockForItem($item, false));
1136 if (in_array($data['type'], ['Create', 'Update', 'Delete'])) {
1137 $data['object'] = $object ?? self::createNote($item);
1138 } elseif ($data['type'] == 'Add') {
1139 $data = self::createAddTag($item, $data);
1140 } elseif ($data['type'] == 'Announce') {
1141 if ($item['verb'] == ACTIVITY::ANNOUNCE) {
1142 $data['object'] = $item['thr-parent'];
1144 $data = self::createAnnounce($item, $data);
1146 } elseif ($data['type'] == 'Follow') {
1147 $data['object'] = $item['parent-uri'];
1148 } elseif ($data['type'] == 'Undo') {
1149 $data['object'] = self::createActivityFromItem($item_id, true);
1151 $data['diaspora:guid'] = $item['guid'];
1152 if (!empty($item['signed_text'])) {
1153 $data['diaspora:like'] = $item['signed_text'];
1155 $data['object'] = $item['thr-parent'];
1158 if (!empty($item['contact-uid'])) {
1159 $uid = $item['contact-uid'];
1161 $uid = $item['uid'];
1164 $owner = User::getOwnerDataById($uid);
1166 Logger::info('Fetched activity', ['item' => $item_id, 'uid' => $uid]);
1168 // We don't sign if we aren't the actor. This is important for relaying content especially for forums
1169 if (!$object_mode && !empty($owner) && ($data['actor'] == $owner['url'])) {
1170 return LDSignature::sign($data, $owner);
1175 /// @todo Create "conversation" entry
1179 * Creates a location entry for a given item array
1181 * @param array $item
1183 * @return array with location array
1185 private static function createLocation($item)
1187 $location = ['type' => 'Place'];
1189 if (!empty($item['location'])) {
1190 $location['name'] = $item['location'];
1195 if (empty($item['coord'])) {
1196 $coord = Map::getCoordinates($item['location']);
1198 $coords = explode(' ', $item['coord']);
1199 if (count($coords) == 2) {
1200 $coord = ['lat' => $coords[0], 'lon' => $coords[1]];
1204 if (!empty($coord['lat']) && !empty($coord['lon'])) {
1205 $location['latitude'] = $coord['lat'];
1206 $location['longitude'] = $coord['lon'];
1213 * Returns a tag array for a given item array
1215 * @param array $item
1217 * @return array of tags
1218 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1220 private static function createTagList($item)
1224 $terms = Tag::getByURIId($item['uri-id'], [Tag::HASHTAG, Tag::MENTION, Tag::IMPLICIT_MENTION, Tag::EXCLUSIVE_MENTION]);
1225 foreach ($terms as $term) {
1226 if ($term['type'] == Tag::HASHTAG) {
1227 $url = DI::baseUrl() . '/search?tag=' . urlencode($term['name']);
1228 $tags[] = ['type' => 'Hashtag', 'href' => $url, 'name' => '#' . $term['name']];
1230 $contact = Contact::getByURL($term['url'], false, ['addr']);
1231 if (empty($contact)) {
1234 if (!empty($contact['addr'])) {
1235 $mention = '@' . $contact['addr'];
1237 $mention = '@' . $term['url'];
1240 $tags[] = ['type' => 'Mention', 'href' => $term['url'], 'name' => $mention];
1244 $announce = self::getAnnounceArray($item);
1245 // Mention the original author upon commented reshares
1246 if (!empty($announce['comment'])) {
1247 $tags[] = ['type' => 'Mention', 'href' => $announce['actor']['url'], 'name' => '@' . $announce['actor']['addr']];
1254 * Adds attachment data to the JSON document
1256 * @param array $item Data of the item that is to be posted
1257 * @param string $type Object type
1259 * @return array with attachment data
1260 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1262 private static function createAttachmentList($item, $type)
1266 $uriids = [$item['uri-id']];
1267 $shared = BBCode::fetchShareAttributes($item['body']);
1268 if (!empty($shared['guid'])) {
1269 $shared_item = Post::selectFirst(['uri-id'], ['guid' => $shared['guid']]);
1270 if (!empty($shared_item['uri-id'])) {
1271 $uriids[] = $shared_item['uri-id'];
1276 foreach ($uriids as $uriid) {
1277 foreach (Post\Media::getByURIId($uriid, [Post\Media::DOCUMENT, Post\Media::TORRENT]) as $attachment) {
1278 if (in_array($attachment['url'], $urls)) {
1281 $urls[] = $attachment['url'];
1283 $attachments[] = ['type' => 'Document',
1284 'mediaType' => $attachment['mimetype'],
1285 'url' => $attachment['url'],
1286 'name' => $attachment['description']];
1290 if ($type != 'Note') {
1291 return $attachments;
1294 foreach ($uriids as $uriid) {
1295 foreach (Post\Media::getByURIId($uriid, [Post\Media::AUDIO, Post\Media::IMAGE, Post\Media::VIDEO]) as $attachment) {
1296 if (in_array($attachment['url'], $urls)) {
1299 $urls[] = $attachment['url'];
1301 $attachments[] = ['type' => 'Document',
1302 'mediaType' => $attachment['mimetype'],
1303 'url' => $attachment['url'],
1304 'name' => $attachment['description']];
1306 // Currently deactivated, since it creates side effects on Mastodon and Pleroma.
1307 // It will be activated, once this cleared.
1309 foreach (Post\Media::getByURIId($uriid, [Post\Media::HTML]) as $attachment) {
1310 if (in_array($attachment['url'], $urls)) {
1313 $urls[] = $attachment['url'];
1315 $attachments[] = ['type' => 'Page',
1316 'mediaType' => $attachment['mimetype'],
1317 'url' => $attachment['url'],
1318 'name' => $attachment['description']];
1322 return $attachments;
1326 * Callback function to replace a Friendica style mention in a mention that is used on AP
1328 * @param array $match Matching values for the callback
1329 * @return string Replaced mention
1330 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1332 private static function mentionCallback($match)
1334 if (empty($match[1])) {
1338 $data = Contact::getByURL($match[1], false, ['url', 'alias', 'nick']);
1339 if (empty($data['nick'])) {
1343 return '[url=' . $data['url'] . ']@' . $data['nick'] . '[/url]';
1347 * Callback function to replace a Friendica style mention in a mention for a summary
1349 * @param array $match Matching values for the callback
1350 * @return string Replaced mention
1351 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1353 private static function mentionAddrCallback($match)
1355 if (empty($match[1])) {
1359 $data = Contact::getByURL($match[1], false, ['addr']);
1360 if (empty($data['addr'])) {
1364 return '@' . $data['addr'];
1368 * Remove image elements since they are added as attachment
1370 * @param string $body
1372 * @return string with removed images
1374 private static function removePictures($body)
1376 // Simplify image codes
1377 $body = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '[img]$3[/img]', $body);
1378 $body = preg_replace("/\[img\=(.*?)\](.*?)\[\/img\]/ism", '[img]$1[/img]', $body);
1380 // Now remove local links
1381 $body = preg_replace_callback(
1382 '/\[url=([^\[\]]*)\]\[img\](.*)\[\/img\]\[\/url\]/Usi',
1384 // We remove the link when it is a link to a local photo page
1385 if (Photo::isLocalPage($match[1])) {
1388 // otherwise we just return the link
1389 return '[url]' . $match[1] . '[/url]';
1394 // Remove all pictures
1395 $body = preg_replace("/\[img\]([^\[\]]*)\[\/img\]/Usi", '', $body);
1401 * Fetches the "context" value for a givem item array from the "conversation" table
1403 * @param array $item
1405 * @return string with context url
1406 * @throws \Exception
1408 private static function fetchContextURLForItem($item)
1410 $conversation = DBA::selectFirst('conversation', ['conversation-href', 'conversation-uri'], ['item-uri' => $item['parent-uri']]);
1411 if (DBA::isResult($conversation) && !empty($conversation['conversation-href'])) {
1412 $context_uri = $conversation['conversation-href'];
1413 } elseif (DBA::isResult($conversation) && !empty($conversation['conversation-uri'])) {
1414 $context_uri = $conversation['conversation-uri'];
1416 $context_uri = $item['parent-uri'] . '#context';
1418 return $context_uri;
1422 * Returns if the post contains sensitive content ("nsfw")
1424 * @param integer $uri_id
1427 * @throws \Exception
1429 private static function isSensitive($uri_id)
1431 return DBA::exists('tag-view', ['uri-id' => $uri_id, 'name' => 'nsfw']);
1435 * Creates event data
1437 * @param array $item
1439 * @return array with the event data
1440 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1442 private static function createEvent($item)
1445 $event['name'] = $item['event-summary'];
1446 $event['content'] = BBCode::convert($item['event-desc'], false, BBCode::ACTIVITYPUB);
1447 $event['startTime'] = DateTimeFormat::utc($item['event-start'] . '+00:00', DateTimeFormat::ATOM);
1449 if (!$item['event-nofinish']) {
1450 $event['endTime'] = DateTimeFormat::utc($item['event-finish'] . '+00:00', DateTimeFormat::ATOM);
1453 if (!empty($item['event-location'])) {
1454 $item['location'] = $item['event-location'];
1455 $event['location'] = self::createLocation($item);
1458 $event['dfrn:adjust'] = (bool)$item['event-adjust'];
1464 * Creates a note/article object array
1466 * @param array $item
1468 * @return array with the object data
1469 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1470 * @throws \ImagickException
1472 public static function createNote($item)
1478 if ($item['event-type'] == 'event') {
1480 } elseif (!empty($item['title'])) {
1486 if ($item['deleted']) {
1487 $type = 'Tombstone';
1491 $data['id'] = $item['uri'];
1492 $data['type'] = $type;
1494 if ($item['deleted']) {
1498 $data['summary'] = BBCode::toPlaintext(BBCode::getAbstract($item['body'], Protocol::ACTIVITYPUB));
1500 if ($item['uri'] != $item['thr-parent']) {
1501 $data['inReplyTo'] = $item['thr-parent'];
1503 $data['inReplyTo'] = null;
1506 $data['diaspora:guid'] = $item['guid'];
1507 $data['published'] = DateTimeFormat::utc($item['created'] . '+00:00', DateTimeFormat::ATOM);
1509 if ($item['created'] != $item['edited']) {
1510 $data['updated'] = DateTimeFormat::utc($item['edited'] . '+00:00', DateTimeFormat::ATOM);
1513 $data['url'] = $item['plink'];
1514 $data['attributedTo'] = $item['author-link'];
1515 $data['sensitive'] = self::isSensitive($item['uri-id']);
1516 $data['context'] = self::fetchContextURLForItem($item);
1518 if (!empty($item['title'])) {
1519 $data['name'] = BBCode::toPlaintext($item['title'], false);
1522 $permission_block = self::createPermissionBlockForItem($item, false);
1524 $body = $item['body'];
1526 if ($type == 'Note') {
1527 $body = $item['raw-body'] ?? self::removePictures($body);
1531 * @todo Improve the automated summary
1532 * This part is currently deactivated. The automated summary seems to be more
1533 * confusing than helping. But possibly we will find a better way.
1534 * So the code is left here for now as a reminder
1536 * } elseif (($type == 'Article') && empty($data['summary'])) {
1537 * $regexp = "/[@!]\[url\=([^\[\]]*)\].*?\[\/url\]/ism";
1538 * $summary = preg_replace_callback($regexp, ['self', 'mentionAddrCallback'], $body);
1539 * $data['summary'] = BBCode::toPlaintext(Plaintext::shorten(self::removePictures($summary), 1000));
1543 if (empty($item['uid']) || !Feature::isEnabled($item['uid'], 'explicit_mentions')) {
1544 $body = self::prependMentions($body, $item['uri-id'], $item['author-link']);
1547 if ($type == 'Event') {
1548 $data = array_merge($data, self::createEvent($item));
1550 $regexp = "/[@!]\[url\=([^\[\]]*)\].*?\[\/url\]/ism";
1551 $body = preg_replace_callback($regexp, ['self', 'mentionCallback'], $body);
1553 $data['content'] = BBCode::convert($body, false, BBCode::ACTIVITYPUB);
1556 // The regular "content" field does contain a minimized HTML. This is done since systems like
1557 // Mastodon has got problems with - for example - embedded pictures.
1558 // The contentMap does contain the unmodified HTML.
1559 $language = self::getLanguage($item);
1560 if (!empty($language)) {
1561 $regexp = "/[@!]\[url\=([^\[\]]*)\].*?\[\/url\]/ism";
1562 $richbody = preg_replace_callback($regexp, ['self', 'mentionCallback'], $item['body']);
1563 $richbody = BBCode::removeAttachment($richbody);
1565 $data['contentMap'][$language] = BBCode::convert($richbody, false, BBCode::EXTERNAL);
1568 $data['source'] = ['content' => $item['body'], 'mediaType' => "text/bbcode"];
1570 if (!empty($item['signed_text']) && ($item['uri'] != $item['thr-parent'])) {
1571 $data['diaspora:comment'] = $item['signed_text'];
1574 $data['attachment'] = self::createAttachmentList($item, $type);
1575 $data['tag'] = self::createTagList($item);
1577 if (empty($data['location']) && (!empty($item['coord']) || !empty($item['location']))) {
1578 $data['location'] = self::createLocation($item);
1581 if (!empty($item['app'])) {
1582 $data['generator'] = ['type' => 'Application', 'name' => $item['app']];
1585 $data = array_merge($data, $permission_block);
1591 * Fetches the language from the post, the user or the system.
1593 * @param array $item
1595 * @return string language string
1597 private static function getLanguage(array $item)
1599 // Try to fetch the language from the post itself
1600 if (!empty($item['language'])) {
1601 $languages = array_keys(json_decode($item['language'], true));
1602 if (!empty($languages[0])) {
1603 return $languages[0];
1607 // Otherwise use the user's language
1608 if (!empty($item['uid'])) {
1609 $user = DBA::selectFirst('user', ['language'], ['uid' => $item['uid']]);
1610 if (!empty($user['language'])) {
1611 return $user['language'];
1615 // And finally just use the system language
1616 return DI::config()->get('system', 'language');
1620 * Creates an an "add tag" entry
1622 * @param array $item
1623 * @param array $data activity data
1625 * @return array with activity data for adding tags
1626 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1627 * @throws \ImagickException
1629 private static function createAddTag($item, $data)
1631 $object = XML::parseString($item['object']);
1632 $target = XML::parseString($item["target"]);
1634 $data['diaspora:guid'] = $item['guid'];
1635 $data['actor'] = $item['author-link'];
1636 $data['target'] = (string)$target->id;
1637 $data['summary'] = BBCode::toPlaintext($item['body']);
1638 $data['object'] = ['id' => (string)$object->id, 'type' => 'tag', 'name' => (string)$object->title, 'content' => (string)$object->content];
1644 * Creates an announce object entry
1646 * @param array $item
1647 * @param array $data activity data
1649 * @return array with activity data
1650 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1651 * @throws \ImagickException
1653 private static function createAnnounce($item, $data)
1655 $orig_body = $item['body'];
1656 $announce = self::getAnnounceArray($item);
1657 if (empty($announce)) {
1658 $data['type'] = 'Create';
1659 $data['object'] = self::createNote($item);
1663 if (empty($announce['comment'])) {
1664 // Pure announce, without a quote
1665 $data['type'] = 'Announce';
1666 $data['object'] = $announce['object']['uri'];
1671 $data['type'] = 'Create';
1672 $item['body'] = $announce['comment'] . "\n" . $announce['object']['plink'];
1673 $data['object'] = self::createNote($item);
1675 /// @todo Finally descide how to implement this in AP. This is a possible way:
1676 $data['object']['attachment'][] = self::createNote($announce['object']);
1678 $data['object']['source']['content'] = $orig_body;
1683 * Return announce related data if the item is an annunce
1685 * @param array $item
1689 public static function getAnnounceArray($item)
1691 $reshared = Item::getShareArray($item);
1692 if (empty($reshared['guid'])) {
1696 $reshared_item = Post::selectFirst(Item::DELIVER_FIELDLIST, ['guid' => $reshared['guid']]);
1697 if (!DBA::isResult($reshared_item)) {
1701 if (!in_array($reshared_item['network'], [Protocol::ACTIVITYPUB, Protocol::DFRN])) {
1705 $profile = APContact::getByURL($reshared_item['author-link'], false);
1706 if (empty($profile)) {
1710 return ['object' => $reshared_item, 'actor' => $profile, 'comment' => $reshared['comment']];
1714 * Checks if the provided item array is an announce
1716 * @param array $item
1720 public static function isAnnounce($item)
1722 if (!empty($item['verb']) && ($item['verb'] == Activity::ANNOUNCE)) {
1726 $announce = self::getAnnounceArray($item);
1727 if (empty($announce)) {
1731 return empty($announce['comment']);
1735 * Creates an activity id for a given contact id
1737 * @param integer $cid Contact ID of target
1739 * @return bool|string activity id
1741 public static function activityIDFromContact($cid)
1743 $contact = DBA::selectFirst('contact', ['uid', 'id', 'created'], ['id' => $cid]);
1744 if (!DBA::isResult($contact)) {
1748 $hash = hash('ripemd128', $contact['uid'].'-'.$contact['id'].'-'.$contact['created']);
1749 $uuid = substr($hash, 0, 8). '-' . substr($hash, 8, 4) . '-' . substr($hash, 12, 4) . '-' . substr($hash, 16, 4) . '-' . substr($hash, 20, 12);
1750 return DI::baseUrl() . '/activity/' . $uuid;
1754 * Transmits a contact suggestion to a given inbox
1756 * @param integer $uid User ID
1757 * @param string $inbox Target inbox
1758 * @param integer $suggestion_id Suggestion ID
1760 * @return boolean was the transmission successful?
1761 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1763 public static function sendContactSuggestion($uid, $inbox, $suggestion_id)
1765 $owner = User::getOwnerDataById($uid);
1767 $suggestion = DI::fsuggest()->getById($suggestion_id);
1769 $data = ['@context' => ActivityPub::CONTEXT,
1770 'id' => DI::baseUrl() . '/activity/' . System::createGUID(),
1771 'type' => 'Announce',
1772 'actor' => $owner['url'],
1773 'object' => $suggestion->url,
1774 'content' => $suggestion->note,
1775 'instrument' => self::getService(),
1776 'to' => [ActivityPub::PUBLIC_COLLECTION],
1779 $signed = LDSignature::sign($data, $owner);
1781 Logger::log('Deliver profile deletion for user ' . $uid . ' to ' . $inbox . ' via ActivityPub', Logger::DEBUG);
1782 return HTTPSignature::transmit($signed, $inbox, $uid);
1786 * Transmits a profile relocation to a given inbox
1788 * @param integer $uid User ID
1789 * @param string $inbox Target inbox
1791 * @return boolean was the transmission successful?
1792 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1794 public static function sendProfileRelocation($uid, $inbox)
1796 $owner = User::getOwnerDataById($uid);
1798 $data = ['@context' => ActivityPub::CONTEXT,
1799 'id' => DI::baseUrl() . '/activity/' . System::createGUID(),
1800 'type' => 'dfrn:relocate',
1801 'actor' => $owner['url'],
1802 'object' => $owner['url'],
1803 'published' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
1804 'instrument' => self::getService(),
1805 'to' => [ActivityPub::PUBLIC_COLLECTION],
1808 $signed = LDSignature::sign($data, $owner);
1810 Logger::log('Deliver profile relocation for user ' . $uid . ' to ' . $inbox . ' via ActivityPub', Logger::DEBUG);
1811 return HTTPSignature::transmit($signed, $inbox, $uid);
1815 * Transmits a profile deletion to a given inbox
1817 * @param integer $uid User ID
1818 * @param string $inbox Target inbox
1820 * @return boolean was the transmission successful?
1821 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1823 public static function sendProfileDeletion($uid, $inbox)
1825 $owner = User::getOwnerDataById($uid);
1827 if (empty($owner)) {
1828 Logger::error('No owner data found, the deletion message cannot be processed.', ['user' => $uid]);
1832 if (empty($owner['uprvkey'])) {
1833 Logger::error('No private key for owner found, the deletion message cannot be processed.', ['user' => $uid]);
1837 $data = ['@context' => ActivityPub::CONTEXT,
1838 'id' => DI::baseUrl() . '/activity/' . System::createGUID(),
1840 'actor' => $owner['url'],
1841 'object' => $owner['url'],
1842 'published' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
1843 'instrument' => self::getService(),
1844 'to' => [ActivityPub::PUBLIC_COLLECTION],
1847 $signed = LDSignature::sign($data, $owner);
1849 Logger::log('Deliver profile deletion for user ' . $uid . ' to ' . $inbox . ' via ActivityPub', Logger::DEBUG);
1850 return HTTPSignature::transmit($signed, $inbox, $uid);
1854 * Transmits a profile change to a given inbox
1856 * @param integer $uid User ID
1857 * @param string $inbox Target inbox
1859 * @return boolean was the transmission successful?
1860 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1861 * @throws \ImagickException
1863 public static function sendProfileUpdate($uid, $inbox)
1865 $owner = User::getOwnerDataById($uid);
1866 $profile = APContact::getByURL($owner['url']);
1868 $data = ['@context' => ActivityPub::CONTEXT,
1869 'id' => DI::baseUrl() . '/activity/' . System::createGUID(),
1871 'actor' => $owner['url'],
1872 'object' => self::getProfile($uid),
1873 'published' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
1874 'instrument' => self::getService(),
1875 'to' => [$profile['followers']],
1878 $signed = LDSignature::sign($data, $owner);
1880 Logger::log('Deliver profile update for user ' . $uid . ' to ' . $inbox . ' via ActivityPub', Logger::DEBUG);
1881 return HTTPSignature::transmit($signed, $inbox, $uid);
1885 * Transmits a given activity to a target
1887 * @param string $activity Type name
1888 * @param string $target Target profile
1889 * @param integer $uid User ID
1891 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1892 * @throws \ImagickException
1893 * @throws \Exception
1895 public static function sendActivity($activity, $target, $uid, $id = '')
1897 $profile = APContact::getByURL($target);
1898 if (empty($profile['inbox'])) {
1899 Logger::warning('No inbox found for target', ['target' => $target, 'profile' => $profile]);
1903 $owner = User::getOwnerDataById($uid);
1906 $id = DI::baseUrl() . '/activity/' . System::createGUID();
1909 $data = ['@context' => ActivityPub::CONTEXT,
1911 'type' => $activity,
1912 'actor' => $owner['url'],
1913 'object' => $profile['url'],
1914 'instrument' => self::getService(),
1915 'to' => [$profile['url']]];
1917 Logger::log('Sending activity ' . $activity . ' to ' . $target . ' for user ' . $uid, Logger::DEBUG);
1919 $signed = LDSignature::sign($data, $owner);
1920 return HTTPSignature::transmit($signed, $profile['inbox'], $uid);
1924 * Transmits a "follow object" activity to a target
1925 * This is a preparation for sending automated "follow" requests when receiving "Announce" messages
1927 * @param string $object Object URL
1928 * @param string $target Target profile
1929 * @param integer $uid User ID
1931 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1932 * @throws \ImagickException
1933 * @throws \Exception
1935 public static function sendFollowObject($object, $target, $uid = 0)
1937 $profile = APContact::getByURL($target);
1938 if (empty($profile['inbox'])) {
1939 Logger::warning('No inbox found for target', ['target' => $target, 'profile' => $profile]);
1944 // Fetch the list of administrators
1945 $admin_mail = explode(',', str_replace(' ', '', DI::config()->get('config', 'admin_email')));
1947 // We need to use some user as a sender. It doesn't care who it will send. We will use an administrator account.
1948 $condition = ['verified' => true, 'blocked' => false, 'account_removed' => false, 'account_expired' => false, 'email' => $admin_mail];
1949 $first_user = DBA::selectFirst('user', ['uid'], $condition);
1950 $uid = $first_user['uid'];
1953 $condition = ['verb' => Activity::FOLLOW, 'uid' => 0, 'parent-uri' => $object,
1954 'author-id' => Contact::getPublicIdByUserId($uid)];
1955 if (Post::exists($condition)) {
1956 Logger::log('Follow for ' . $object . ' for user ' . $uid . ' does already exist.', Logger::DEBUG);
1960 $owner = User::getOwnerDataById($uid);
1962 $data = ['@context' => ActivityPub::CONTEXT,
1963 'id' => DI::baseUrl() . '/activity/' . System::createGUID(),
1965 'actor' => $owner['url'],
1966 'object' => $object,
1967 'instrument' => self::getService(),
1968 'to' => [$profile['url']]];
1970 Logger::log('Sending follow ' . $object . ' to ' . $target . ' for user ' . $uid, Logger::DEBUG);
1972 $signed = LDSignature::sign($data, $owner);
1973 return HTTPSignature::transmit($signed, $profile['inbox'], $uid);
1977 * Transmit a message that the contact request had been accepted
1979 * @param string $target Target profile
1981 * @param integer $uid User ID
1982 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1983 * @throws \ImagickException
1985 public static function sendContactAccept($target, $id, $uid)
1987 $profile = APContact::getByURL($target);
1988 if (empty($profile['inbox'])) {
1989 Logger::warning('No inbox found for target', ['target' => $target, 'profile' => $profile]);
1993 $owner = User::getOwnerDataById($uid);
1994 $data = ['@context' => ActivityPub::CONTEXT,
1995 'id' => DI::baseUrl() . '/activity/' . System::createGUID(),
1997 'actor' => $owner['url'],
1999 'id' => (string)$id,
2001 'actor' => $profile['url'],
2002 'object' => $owner['url']
2004 'instrument' => self::getService(),
2005 'to' => [$profile['url']]];
2007 Logger::debug('Sending accept to ' . $target . ' for user ' . $uid . ' with id ' . $id);
2009 $signed = LDSignature::sign($data, $owner);
2010 HTTPSignature::transmit($signed, $profile['inbox'], $uid);
2014 * Reject a contact request or terminates the contact relation
2016 * @param string $target Target profile
2018 * @param integer $uid User ID
2019 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2020 * @throws \ImagickException
2022 public static function sendContactReject($target, $id, $uid)
2024 $profile = APContact::getByURL($target);
2025 if (empty($profile['inbox'])) {
2026 Logger::warning('No inbox found for target', ['target' => $target, 'profile' => $profile]);
2030 $owner = User::getOwnerDataById($uid);
2031 $data = ['@context' => ActivityPub::CONTEXT,
2032 'id' => DI::baseUrl() . '/activity/' . System::createGUID(),
2034 'actor' => $owner['url'],
2036 'id' => (string)$id,
2038 'actor' => $profile['url'],
2039 'object' => $owner['url']
2041 'instrument' => self::getService(),
2042 'to' => [$profile['url']]];
2044 Logger::debug('Sending reject to ' . $target . ' for user ' . $uid . ' with id ' . $id);
2046 $signed = LDSignature::sign($data, $owner);
2047 HTTPSignature::transmit($signed, $profile['inbox'], $uid);
2051 * Transmits a message that we don't want to follow this contact anymore
2053 * @param string $target Target profile
2054 * @param integer $uid User ID
2055 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2056 * @throws \ImagickException
2057 * @throws \Exception
2058 * @return bool success
2060 public static function sendContactUndo($target, $cid, $uid)
2062 $profile = APContact::getByURL($target);
2063 if (empty($profile['inbox'])) {
2064 Logger::warning('No inbox found for target', ['target' => $target, 'profile' => $profile]);
2068 $object_id = self::activityIDFromContact($cid);
2069 if (empty($object_id)) {
2073 $id = DI::baseUrl() . '/activity/' . System::createGUID();
2075 $owner = User::getOwnerDataById($uid);
2076 $data = ['@context' => ActivityPub::CONTEXT,
2079 'actor' => $owner['url'],
2080 'object' => ['id' => $object_id, 'type' => 'Follow',
2081 'actor' => $owner['url'],
2082 'object' => $profile['url']],
2083 'instrument' => self::getService(),
2084 'to' => [$profile['url']]];
2086 Logger::log('Sending undo to ' . $target . ' for user ' . $uid . ' with id ' . $id, Logger::DEBUG);
2088 $signed = LDSignature::sign($data, $owner);
2089 return HTTPSignature::transmit($signed, $profile['inbox'], $uid);
2092 private static function prependMentions($body, int $uriid, string $authorLink)
2096 foreach (Tag::getByURIId($uriid, [Tag::IMPLICIT_MENTION]) as $tag) {
2097 $profile = Contact::getByURL($tag['url'], false, ['addr', 'contact-type', 'nick']);
2098 if (!empty($profile['addr'])
2099 && $profile['contact-type'] != Contact::TYPE_COMMUNITY
2100 && !strstr($body, $profile['addr'])
2101 && !strstr($body, $tag['url'])
2102 && $tag['url'] !== $authorLink
2104 $mentions[] = '@[url=' . $tag['url'] . ']' . $profile['nick'] . '[/url]';
2108 $mentions[] = $body;
2110 return implode(' ', $mentions);