3 * @copyright Copyright (C) 2020, Friendica
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\Item;
37 use Friendica\Model\ItemURI;
38 use Friendica\Model\Profile;
39 use Friendica\Model\Photo;
40 use Friendica\Model\Post;
41 use Friendica\Model\Tag;
42 use Friendica\Model\User;
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 $contacts = DBA::select('apcontact', ['inbox'],
71 ["`type` = ? AND `url` IN (SELECT `url` FROM `contact` WHERE `uid` = ? AND `rel` IN (?, ?))",
72 'Application', 0, Contact::FOLLOWER, Contact::FRIEND]);
73 while ($contact = DBA::fetch($contacts)) {
74 $inboxes[$contact['inbox']] = $contact['inbox'];
76 DBA::close($contacts);
82 * Add relay servers to the list of inboxes
84 * @param array $inboxes
85 * @return array inboxes with added relay servers
87 public static function addRelayServerInboxesForItem(int $item_id, array $inboxes = [])
89 $item = Item::selectFirst(['uid'], ['id' => $item_id]);
94 $relays = Relay::getList($item_id, [], [Protocol::ACTIVITYPUB]);
99 foreach ($relays as $relay) {
100 $contact = Contact::getByURLForUser($relay['url'], $item['uid'], false, ['id']);
101 $inboxes[$relay['batch']][] = $contact['id'] ?? 0;
107 * Subscribe to a relay
109 * @param string $url Subscribe actor url
110 * @return bool success
112 public static function sendRelayFollow(string $url)
114 $contact = Contact::getByURL($url);
115 if (empty($contact)) {
119 $activity_id = ActivityPub\Transmitter::activityIDFromContact($contact['id']);
120 $success = ActivityPub\Transmitter::sendActivity('Follow', $url, 0, $activity_id);
122 $rel = $contact['rel'] == Contact::SHARING ? Contact::FRIEND : Contact::FOLLOWER;
123 DBA::update('contact', ['rel' => $rel], ['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 $rel = $contact['rel'] == Contact::FRIEND ? Contact::SHARING : Contact::NOTHING;
146 DBA::update('contact', ['rel' => $rel], ['id' => $contact['id']]);
153 * Collects a list of contacts of the given owner
155 * @param array $owner Owner array
156 * @param int|array $rel The relevant value(s) contact.rel should match
157 * @param string $module The name of the relevant AP endpoint module (followers|following)
158 * @param integer $page Page number
160 * @return array of owners
163 public static function getContacts($owner, $rel, $module, $page = null)
167 'uid' => $owner['uid'],
175 $condition = DBA::buildCondition($parameters);
177 $sql = "SELECT COUNT(*) as `count`
179 JOIN `apcontact` ON `apcontact`.`url` = `contact`.`url`
182 $contacts = DBA::fetchFirst($sql, ...$parameters);
184 $modulePath = '/' . $module . '/';
186 $data = ['@context' => ActivityPub::CONTEXT];
187 $data['id'] = DI::baseUrl() . $modulePath . $owner['nickname'];
188 $data['type'] = 'OrderedCollection';
189 $data['totalItems'] = $contacts['count'];
191 // When we hide our friends we will only show the pure number but don't allow more.
192 $profile = Profile::getByUID($owner['uid']);
193 if (!empty($profile['hide-friends'])) {
198 $data['first'] = DI::baseUrl() . $modulePath . $owner['nickname'] . '?page=1';
200 $data['type'] = 'OrderedCollectionPage';
203 $sql = "SELECT `contact`.`url`
205 JOIN `apcontact` ON `apcontact`.`url` = `contact`.`url`
209 $parameters[] = ($page - 1) * 100;
212 $contacts = DBA::p($sql, ...$parameters);
213 while ($contact = DBA::fetch($contacts)) {
214 $list[] = $contact['url'];
216 DBA::close($contacts);
219 $data['next'] = DI::baseUrl() . $modulePath . $owner['nickname'] . '?page=' . ($page + 1);
222 $data['partOf'] = DI::baseUrl() . $modulePath . $owner['nickname'];
224 $data['orderedItems'] = $list;
231 * Public posts for the given owner
233 * @param array $owner Owner array
234 * @param integer $page Page number
235 * @param string $requester URL of requesting account
237 * @return array of posts
238 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
239 * @throws \ImagickException
241 public static function getOutbox($owner, $page = null, $requester = '')
243 $public_contact = Contact::getIdForURL($owner['url']);
244 $condition = ['uid' => 0, 'contact-id' => $public_contact,
245 'private' => [Item::PUBLIC, Item::UNLISTED]];
247 if (!empty($requester)) {
248 $requester_id = Contact::getIdForURL($requester, $owner['uid']);
249 if (!empty($requester_id)) {
250 $permissionSets = DI::permissionSet()->selectByContactId($requester_id, $owner['uid']);
251 if (!empty($permissionSets)) {
252 $condition = ['uid' => $owner['uid'], 'origin' => true,
253 'psid' => array_merge($permissionSets->column('id'),
254 [DI::permissionSet()->getIdFromACL($owner['uid'], '', '', '', '')])];
259 $condition = array_merge($condition,
260 ['author-id' => $public_contact,
261 'gravity' => [GRAVITY_PARENT, GRAVITY_COMMENT],
262 'deleted' => false, 'visible' => true, 'moderated' => false]);
264 $count = DBA::count('item', $condition);
266 $data = ['@context' => ActivityPub::CONTEXT];
267 $data['id'] = DI::baseUrl() . '/outbox/' . $owner['nickname'];
268 $data['type'] = 'OrderedCollection';
269 $data['totalItems'] = $count;
272 $data['first'] = DI::baseUrl() . '/outbox/' . $owner['nickname'] . '?page=1';
274 $data['type'] = 'OrderedCollectionPage';
277 $condition['parent-network'] = Protocol::NATIVE_SUPPORT;
279 $items = Item::select(['id'], $condition, ['limit' => [($page - 1) * 20, 20], 'order' => ['created' => true]]);
280 while ($item = Item::fetch($items)) {
281 $activity = self::createActivityFromItem($item['id'], true);
282 $activity['type'] = $activity['type'] == 'Update' ? 'Create' : $activity['type'];
284 // Only list "Create" activity objects here, no reshares
285 if (!empty($activity['object']) && ($activity['type'] == 'Create')) {
286 $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 Item::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'], ['id' => $cid]);
570 if (!DBA::isResult($contact) || (!in_array($contact['network'], $networks) && ($contact['protocol'] != Protocol::ACTIVITYPUB))) {
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'], ['id' => $receiver]);
582 if (!DBA::isResult($contact) || (!in_array($contact['network'], $networks) && ($contact['protocol'] != Protocol::ACTIVITYPUB))) {
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 = Item::select(['id', 'author-link', 'owner-link', 'gravity', 'uri'], ['parent' => $item['parent']]);
598 while ($parent = Item::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 * Fetches a list of inboxes of followers of a given user
697 * @param integer $uid User ID
698 * @param boolean $personal fetch personal inboxes
699 * @param boolean $all_ap Retrieve all AP enabled inboxes
701 * @return array of follower inboxes
702 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
703 * @throws \ImagickException
705 public static function fetchTargetInboxesforUser($uid, $personal = false, bool $all_ap = false)
711 if (!empty($item['uid'])) {
712 $profile = User::getOwnerDataById($item['uid']);
713 if (!empty($profile)) {
714 $isforum = $profile['account-type'] == User::ACCOUNT_TYPE_COMMUNITY;
718 if (DI::config()->get('debug', 'total_ap_delivery') || $all_ap) {
719 // Will be activated in a later step
720 $networks = Protocol::FEDERATED;
722 // For now only send to these contacts:
723 $networks = [Protocol::ACTIVITYPUB, Protocol::OSTATUS];
726 $condition = ['uid' => $uid, 'archive' => false, 'pending' => false, 'blocked' => false];
729 $condition['rel'] = [Contact::FOLLOWER, Contact::FRIEND];
732 $contacts = DBA::select('contact', ['id', 'url', 'network', 'protocol'], $condition);
733 while ($contact = DBA::fetch($contacts)) {
734 if (Contact::isLocal($contact['url'])) {
738 if (!in_array($contact['network'], $networks) && ($contact['protocol'] != Protocol::ACTIVITYPUB)) {
742 if ($isforum && ($contact['network'] == Protocol::DFRN)) {
746 if (Network::isUrlBlocked($contact['url'])) {
750 $profile = APContact::getByURL($contact['url'], false);
751 if (!empty($profile)) {
752 if (empty($profile['sharedinbox']) || $personal) {
753 $target = $profile['inbox'];
755 $target = $profile['sharedinbox'];
757 if (!self::archivedInbox($target)) {
758 $inboxes[$target][] = $contact['id'];
762 DBA::close($contacts);
768 * Fetches an array of inboxes for the given item and user
770 * @param array $item Item array
771 * @param integer $uid User ID
772 * @param boolean $personal fetch personal inboxes
773 * @param integer $last_id Last item id for adding receivers
774 * @param boolean $forum_mode "true" means that we are sending content to a forum
775 * @return array with inboxes
776 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
777 * @throws \ImagickException
779 public static function fetchTargetInboxes($item, $uid, $personal = false, $last_id = 0, $forum_mode = false)
781 $permissions = self::createPermissionBlockForItem($item, true, $last_id, $forum_mode);
782 if (empty($permissions)) {
788 if ($item['gravity'] == GRAVITY_ACTIVITY) {
789 $item_profile = APContact::getByURL($item['author-link'], false);
791 $item_profile = APContact::getByURL($item['owner-link'], false);
794 if (empty($item_profile)) {
798 $profile_uid = User::getIdForURL($item_profile['url']);
800 foreach (['to', 'cc', 'bto', 'bcc'] as $element) {
801 if (empty($permissions[$element])) {
805 $blindcopy = in_array($element, ['bto', 'bcc']);
807 foreach ($permissions[$element] as $receiver) {
808 if (empty($receiver) || Network::isUrlBlocked($receiver)) {
812 if ($item_profile && ($receiver == $item_profile['followers']) && ($uid == $profile_uid)) {
813 $inboxes = array_merge($inboxes, self::fetchTargetInboxesforUser($uid, $personal, self::isAPPost($last_id)));
815 if (Contact::isLocal($receiver)) {
819 $profile = APContact::getByURL($receiver, false);
820 if (!empty($profile)) {
821 $contact = Contact::getByURLForUser($receiver, $uid, false, ['id']);
823 if (empty($profile['sharedinbox']) || $personal || $blindcopy) {
824 $target = $profile['inbox'];
826 $target = $profile['sharedinbox'];
828 if (!self::archivedInbox($target)) {
829 $inboxes[$target][] = $contact['id'] ?? 0;
840 * Creates an array in the structure of the item table for a given mail id
842 * @param integer $mail_id
847 public static function ItemArrayFromMail($mail_id)
849 $mail = DBA::selectFirst('mail', [], ['id' => $mail_id]);
850 if (!DBA::isResult($mail)) {
854 $mail['uri-id'] = ItemURI::insert(['uri' => $mail['uri'], 'guid' => $mail['guid']]);
856 $reply = DBA::selectFirst('mail', ['uri'], ['parent-uri' => $mail['parent-uri'], 'reply' => false]);
858 // Making the post more compatible for Mastodon by:
859 // - Making it a note and not an article (no title)
860 // - Moving the title into the "summary" field that is used as a "content warning"
861 $mail['body'] = '[abstract]' . $mail['title'] . "[/abstract]\n" . $mail['body'];
864 $mail['author-link'] = $mail['owner-link'] = $mail['from-url'];
865 $mail['allow_cid'] = '<'.$mail['contact-id'].'>';
866 $mail['allow_gid'] = '';
867 $mail['deny_cid'] = '';
868 $mail['deny_gid'] = '';
869 $mail['private'] = true;
870 $mail['deleted'] = false;
871 $mail['edited'] = $mail['created'];
872 $mail['plink'] = $mail['uri'];
873 $mail['thr-parent'] = $reply['uri'];
874 $mail['gravity'] = ($mail['reply'] ? GRAVITY_COMMENT: GRAVITY_PARENT);
876 $mail['event-type'] = '';
884 * Creates an activity array for a given mail id
886 * @param integer $mail_id
887 * @param boolean $object_mode Is the activity item is used inside another object?
889 * @return array of activity
892 public static function createActivityFromMail($mail_id, $object_mode = false)
894 $mail = self::ItemArrayFromMail($mail_id);
898 $object = self::createNote($mail);
901 $data = ['@context' => ActivityPub::CONTEXT];
906 $data['id'] = $mail['uri'] . '/Create';
907 $data['type'] = 'Create';
908 $data['actor'] = $mail['author-link'];
909 $data['published'] = DateTimeFormat::utc($mail['created'] . '+00:00', DateTimeFormat::ATOM);
910 $data['instrument'] = self::getService();
911 $data = array_merge($data, self::createPermissionBlockForItem($mail, true));
913 if (empty($data['to']) && !empty($data['cc'])) {
914 $data['to'] = $data['cc'];
917 if (empty($data['to']) && !empty($data['bcc'])) {
918 $data['to'] = $data['bcc'];
924 $object['to'] = $data['to'];
925 $object['tag'] = [['type' => 'Mention', 'href' => $object['to'][0], 'name' => '']];
927 unset($object['cc']);
928 unset($object['bcc']);
930 $data['directMessage'] = true;
932 $data['object'] = $object;
934 $owner = User::getOwnerDataById($mail['uid']);
936 if (!$object_mode && !empty($owner)) {
937 return LDSignature::sign($data, $owner);
944 * Returns the activity type of a given item
948 * @return string with activity type
949 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
950 * @throws \ImagickException
952 private static function getTypeOfItem($item)
956 // Only check for a reshare, if it is a real reshare and no quoted reshare
957 if (strpos($item['body'], "[share") === 0) {
958 $announce = self::getAnnounceArray($item);
959 $reshared = !empty($announce);
964 } elseif ($item['verb'] == Activity::POST) {
965 if ($item['created'] == $item['edited']) {
970 } elseif ($item['verb'] == Activity::LIKE) {
972 } elseif ($item['verb'] == Activity::DISLIKE) {
974 } elseif ($item['verb'] == Activity::ATTEND) {
976 } elseif ($item['verb'] == Activity::ATTENDNO) {
978 } elseif ($item['verb'] == Activity::ATTENDMAYBE) {
979 $type = 'TentativeAccept';
980 } elseif ($item['verb'] == Activity::FOLLOW) {
982 } elseif ($item['verb'] == Activity::TAG) {
984 } elseif ($item['verb'] == Activity::ANNOUNCE) {
994 * Creates the activity or fetches it from the cache
996 * @param integer $item_id
997 * @param boolean $force Force new cache entry
999 * @return array with the activity
1000 * @throws \Exception
1002 public static function createCachedActivityFromItem($item_id, $force = false)
1004 $cachekey = 'APDelivery:createActivity:' . $item_id;
1007 $data = DI::cache()->get($cachekey);
1008 if (!is_null($data)) {
1013 $data = self::createActivityFromItem($item_id);
1015 DI::cache()->set($cachekey, $data, Duration::QUARTER_HOUR);
1020 * Creates an activity array for a given item id
1022 * @param integer $item_id
1023 * @param boolean $object_mode Is the activity item is used inside another object?
1025 * @return false|array
1026 * @throws \Exception
1028 public static function createActivityFromItem(int $item_id, bool $object_mode = false)
1030 Logger::info('Fetching activity', ['item' => $item_id]);
1031 $item = Item::selectFirst([], ['id' => $item_id, 'parent-network' => Protocol::NATIVE_SUPPORT]);
1032 if (!DBA::isResult($item)) {
1036 // In case of a forum post ensure to return the original post if author and forum are on the same machine
1037 if (!empty($item['forum_mode'])) {
1038 $author = Contact::getById($item['author-id'], ['nurl']);
1039 if (!empty($author['nurl'])) {
1040 $self = Contact::selectFirst(['uid'], ['nurl' => $author['nurl'], 'self' => true]);
1041 if (!empty($self['uid'])) {
1042 $forum_item = Item::selectFirst([], ['uri-id' => $item['uri-id'], 'uid' => $self['uid']]);
1043 if (DBA::isResult($item)) {
1044 $item = $forum_item;
1050 if (empty($item['uri-id'])) {
1051 Logger::warning('Item without uri-id', ['item' => $item]);
1055 $condition = ['item-uri' => $item['uri'], 'protocol' => Conversation::PARCEL_ACTIVITYPUB];
1056 $conversation = DBA::selectFirst('conversation', ['source'], $condition);
1057 if (!$item['origin'] && DBA::isResult($conversation)) {
1058 $data = json_decode($conversation['source'], true);
1059 if (!empty($data['type'])) {
1060 if (in_array($data['type'], ['Create', 'Update'])) {
1062 unset($data['@context']);
1063 unset($data['signature']);
1065 Logger::info('Return stored conversation', ['item' => $item_id]);
1067 } elseif (in_array('as:' . $data['type'], Receiver::CONTENT_TYPES)) {
1068 if (!empty($data['@context'])) {
1069 $context = $data['@context'];
1070 unset($data['@context']);
1072 unset($data['actor']);
1078 $type = self::getTypeOfItem($item);
1080 if (!$object_mode) {
1081 $data = ['@context' => $context ?? ActivityPub::CONTEXT];
1083 if ($item['deleted'] && ($item['gravity'] == GRAVITY_ACTIVITY)) {
1085 } elseif ($item['deleted']) {
1092 if (($item['gravity'] == GRAVITY_ACTIVITY) && ($type != 'Undo')) {
1093 $data['id'] = $item['uri'];
1095 $data['id'] = $item['uri'] . '/' . $type;
1098 $data['type'] = $type;
1100 if (($type != 'Announce') || ($item['gravity'] != GRAVITY_PARENT)) {
1101 $data['actor'] = $item['author-link'];
1103 $data['actor'] = $item['owner-link'];
1106 $data['published'] = DateTimeFormat::utc($item['created'] . '+00:00', DateTimeFormat::ATOM);
1108 $data['instrument'] = self::getService();
1110 $data = array_merge($data, self::createPermissionBlockForItem($item, false));
1112 if (in_array($data['type'], ['Create', 'Update', 'Delete'])) {
1113 $data['object'] = $object ?? self::createNote($item);
1114 } elseif ($data['type'] == 'Add') {
1115 $data = self::createAddTag($item, $data);
1116 } elseif ($data['type'] == 'Announce') {
1117 if ($item['verb'] == ACTIVITY::ANNOUNCE) {
1118 $data['object'] = $item['thr-parent'];
1120 $data = self::createAnnounce($item, $data);
1122 } elseif ($data['type'] == 'Follow') {
1123 $data['object'] = $item['parent-uri'];
1124 } elseif ($data['type'] == 'Undo') {
1125 $data['object'] = self::createActivityFromItem($item_id, true);
1127 $data['diaspora:guid'] = $item['guid'];
1128 if (!empty($item['signed_text'])) {
1129 $data['diaspora:like'] = $item['signed_text'];
1131 $data['object'] = $item['thr-parent'];
1134 if (!empty($item['contact-uid'])) {
1135 $uid = $item['contact-uid'];
1137 $uid = $item['uid'];
1140 $owner = User::getOwnerDataById($uid);
1142 Logger::info('Fetched activity', ['item' => $item_id, 'uid' => $uid]);
1144 // We don't sign if we aren't the actor. This is important for relaying content especially for forums
1145 if (!$object_mode && !empty($owner) && ($data['actor'] == $owner['url'])) {
1146 return LDSignature::sign($data, $owner);
1151 /// @todo Create "conversation" entry
1155 * Creates a location entry for a given item array
1157 * @param array $item
1159 * @return array with location array
1161 private static function createLocation($item)
1163 $location = ['type' => 'Place'];
1165 if (!empty($item['location'])) {
1166 $location['name'] = $item['location'];
1171 if (empty($item['coord'])) {
1172 $coord = Map::getCoordinates($item['location']);
1174 $coords = explode(' ', $item['coord']);
1175 if (count($coords) == 2) {
1176 $coord = ['lat' => $coords[0], 'lon' => $coords[1]];
1180 if (!empty($coord['lat']) && !empty($coord['lon'])) {
1181 $location['latitude'] = $coord['lat'];
1182 $location['longitude'] = $coord['lon'];
1189 * Returns a tag array for a given item array
1191 * @param array $item
1193 * @return array of tags
1194 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1196 private static function createTagList($item)
1200 $terms = Tag::getByURIId($item['uri-id'], [Tag::HASHTAG, Tag::MENTION, Tag::IMPLICIT_MENTION, Tag::EXCLUSIVE_MENTION]);
1201 foreach ($terms as $term) {
1202 if ($term['type'] == Tag::HASHTAG) {
1203 $url = DI::baseUrl() . '/search?tag=' . urlencode($term['name']);
1204 $tags[] = ['type' => 'Hashtag', 'href' => $url, 'name' => '#' . $term['name']];
1206 $contact = Contact::getByURL($term['url'], false, ['addr']);
1207 if (empty($contact)) {
1210 if (!empty($contact['addr'])) {
1211 $mention = '@' . $contact['addr'];
1213 $mention = '@' . $term['url'];
1216 $tags[] = ['type' => 'Mention', 'href' => $term['url'], 'name' => $mention];
1220 $announce = self::getAnnounceArray($item);
1221 // Mention the original author upon commented reshares
1222 if (!empty($announce['comment'])) {
1223 $tags[] = ['type' => 'Mention', 'href' => $announce['actor']['url'], 'name' => '@' . $announce['actor']['addr']];
1230 * Adds attachment data to the JSON document
1232 * @param array $item Data of the item that is to be posted
1233 * @param string $type Object type
1235 * @return array with attachment data
1236 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1238 private static function createAttachmentList($item, $type)
1242 // Currently deactivated, since it creates side effects on Mastodon and Pleroma.
1243 // It will be reactivated, once this cleared.
1245 $attach_data = BBCode::getAttachmentData($item['body']);
1246 if (!empty($attach_data['url'])) {
1247 $attachment = ['type' => 'Page',
1248 'mediaType' => 'text/html',
1249 'url' => $attach_data['url']];
1251 if (!empty($attach_data['title'])) {
1252 $attachment['name'] = $attach_data['title'];
1255 if (!empty($attach_data['description'])) {
1256 $attachment['summary'] = $attach_data['description'];
1259 if (!empty($attach_data['image'])) {
1260 $imgdata = Images::getInfoFromURLCached($attach_data['image']);
1262 $attachment['icon'] = ['type' => 'Image',
1263 'mediaType' => $imgdata['mime'],
1264 'width' => $imgdata[0],
1265 'height' => $imgdata[1],
1266 'url' => $attach_data['image']];
1270 $attachments[] = $attachment;
1273 foreach (Post\Media::getByURIId($item['uri-id'], [Post\Media::DOCUMENT, Post\Media::TORRENT, Post\Media::UNKNOWN]) as $attachment) {
1274 $attachments[] = ['type' => 'Document',
1275 'mediaType' => $attachment['mimetype'],
1276 'url' => $attachment['url'],
1277 'name' => $attachment['description']];
1280 if ($type != 'Note') {
1281 return $attachments;
1284 foreach (Post\Media::getByURIId($item['uri-id'], [Post\Media::AUDIO, Post\Media::IMAGE, Post\Media::VIDEO]) as $attachment) {
1285 $attachments[] = ['type' => 'Document',
1286 'mediaType' => $attachment['mimetype'],
1287 'url' => $attachment['url'],
1288 'name' => $attachment['description']];
1291 return $attachments;
1295 * Callback function to replace a Friendica style mention in a mention that is used on AP
1297 * @param array $match Matching values for the callback
1298 * @return string Replaced mention
1299 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1301 private static function mentionCallback($match)
1303 if (empty($match[1])) {
1307 $data = Contact::getByURL($match[1], false, ['url', 'alias', 'nick']);
1308 if (empty($data['nick'])) {
1312 return '[url=' . ($data['alias'] ?: $data['url']) . ']@' . $data['nick'] . '[/url]';
1316 * Remove image elements since they are added as attachment
1318 * @param string $body
1320 * @return string with removed images
1322 private static function removePictures($body)
1324 // Simplify image codes
1325 $body = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '[img]$3[/img]', $body);
1326 $body = preg_replace("/\[img\=(.*?)\](.*?)\[\/img\]/ism", '[img]$1[/img]', $body);
1328 // Now remove local links
1329 $body = preg_replace_callback(
1330 '/\[url=([^\[\]]*)\]\[img\](.*)\[\/img\]\[\/url\]/Usi',
1332 // We remove the link when it is a link to a local photo page
1333 if (Photo::isLocalPage($match[1])) {
1336 // otherwise we just return the link
1337 return '[url]' . $match[1] . '[/url]';
1342 // Remove all pictures
1343 $body = preg_replace("/\[img\]([^\[\]]*)\[\/img\]/Usi", '', $body);
1349 * Fetches the "context" value for a givem item array from the "conversation" table
1351 * @param array $item
1353 * @return string with context url
1354 * @throws \Exception
1356 private static function fetchContextURLForItem($item)
1358 $conversation = DBA::selectFirst('conversation', ['conversation-href', 'conversation-uri'], ['item-uri' => $item['parent-uri']]);
1359 if (DBA::isResult($conversation) && !empty($conversation['conversation-href'])) {
1360 $context_uri = $conversation['conversation-href'];
1361 } elseif (DBA::isResult($conversation) && !empty($conversation['conversation-uri'])) {
1362 $context_uri = $conversation['conversation-uri'];
1364 $context_uri = $item['parent-uri'] . '#context';
1366 return $context_uri;
1370 * Returns if the post contains sensitive content ("nsfw")
1372 * @param integer $uri_id
1375 * @throws \Exception
1377 private static function isSensitive($uri_id)
1379 return DBA::exists('tag-view', ['uri-id' => $uri_id, 'name' => 'nsfw']);
1383 * Creates event data
1385 * @param array $item
1387 * @return array with the event data
1388 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1390 public static function createEvent($item)
1393 $event['name'] = $item['event-summary'];
1394 $event['content'] = BBCode::convert($item['event-desc'], false, BBCode::ACTIVITYPUB);
1395 $event['startTime'] = DateTimeFormat::utc($item['event-start'] . '+00:00', DateTimeFormat::ATOM);
1397 if (!$item['event-nofinish']) {
1398 $event['endTime'] = DateTimeFormat::utc($item['event-finish'] . '+00:00', DateTimeFormat::ATOM);
1401 if (!empty($item['event-location'])) {
1402 $item['location'] = $item['event-location'];
1403 $event['location'] = self::createLocation($item);
1410 * Creates a note/article object array
1412 * @param array $item
1414 * @return array with the object data
1415 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1416 * @throws \ImagickException
1418 public static function createNote($item)
1424 if ($item['event-type'] == 'event') {
1426 } elseif (!empty($item['title'])) {
1432 if ($item['deleted']) {
1433 $type = 'Tombstone';
1437 $data['id'] = $item['uri'];
1438 $data['type'] = $type;
1440 if ($item['deleted']) {
1444 $data['summary'] = BBCode::toPlaintext(BBCode::getAbstract($item['body'], Protocol::ACTIVITYPUB));
1446 if ($item['uri'] != $item['thr-parent']) {
1447 $data['inReplyTo'] = $item['thr-parent'];
1449 $data['inReplyTo'] = null;
1452 $data['diaspora:guid'] = $item['guid'];
1453 $data['published'] = DateTimeFormat::utc($item['created'] . '+00:00', DateTimeFormat::ATOM);
1455 if ($item['created'] != $item['edited']) {
1456 $data['updated'] = DateTimeFormat::utc($item['edited'] . '+00:00', DateTimeFormat::ATOM);
1459 $data['url'] = $item['plink'];
1460 $data['attributedTo'] = $item['author-link'];
1461 $data['sensitive'] = self::isSensitive($item['uri-id']);
1462 $data['context'] = self::fetchContextURLForItem($item);
1464 if (!empty($item['title'])) {
1465 $data['name'] = BBCode::toPlaintext($item['title'], false);
1468 $permission_block = self::createPermissionBlockForItem($item, false);
1470 $body = $item['body'];
1472 if ($type == 'Note') {
1473 $body = $item['raw-body'] ?? self::removePictures($body);
1474 } elseif (($type == 'Article') && empty($data['summary'])) {
1475 $data['summary'] = BBCode::toPlaintext(Plaintext::shorten(self::removePictures($body), 1000));
1478 if (empty($item['uid']) || !Feature::isEnabled($item['uid'], 'explicit_mentions')) {
1479 $body = self::prependMentions($body, $item['uri-id'], $item['author-link']);
1482 if ($type == 'Event') {
1483 $data = array_merge($data, self::createEvent($item));
1485 $regexp = "/[@!]\[url\=([^\[\]]*)\].*?\[\/url\]/ism";
1486 $body = preg_replace_callback($regexp, ['self', 'mentionCallback'], $body);
1488 $data['content'] = BBCode::convert($body, false, BBCode::ACTIVITYPUB);
1491 // The regular "content" field does contain a minimized HTML. This is done since systems like
1492 // Mastodon has got problems with - for example - embedded pictures.
1493 // The contentMap does contain the unmodified HTML.
1494 $language = self::getLanguage($item);
1495 if (!empty($language)) {
1496 $regexp = "/[@!]\[url\=([^\[\]]*)\].*?\[\/url\]/ism";
1497 $richbody = preg_replace_callback($regexp, ['self', 'mentionCallback'], $item['body']);
1498 $richbody = BBCode::removeAttachment($richbody);
1500 $data['contentMap'][$language] = BBCode::convert($richbody, false);
1503 $data['source'] = ['content' => $item['body'], 'mediaType' => "text/bbcode"];
1505 if (!empty($item['signed_text']) && ($item['uri'] != $item['thr-parent'])) {
1506 $data['diaspora:comment'] = $item['signed_text'];
1509 $data['attachment'] = self::createAttachmentList($item, $type);
1510 $data['tag'] = self::createTagList($item);
1512 if (empty($data['location']) && (!empty($item['coord']) || !empty($item['location']))) {
1513 $data['location'] = self::createLocation($item);
1516 if (!empty($item['app'])) {
1517 $data['generator'] = ['type' => 'Application', 'name' => $item['app']];
1520 $data = array_merge($data, $permission_block);
1526 * Fetches the language from the post, the user or the system.
1528 * @param array $item
1530 * @return string language string
1532 private static function getLanguage(array $item)
1534 // Try to fetch the language from the post itself
1535 if (!empty($item['language'])) {
1536 $languages = array_keys(json_decode($item['language'], true));
1537 if (!empty($languages[0])) {
1538 return $languages[0];
1542 // Otherwise use the user's language
1543 if (!empty($item['uid'])) {
1544 $user = DBA::selectFirst('user', ['language'], ['uid' => $item['uid']]);
1545 if (!empty($user['language'])) {
1546 return $user['language'];
1550 // And finally just use the system language
1551 return DI::config()->get('system', 'language');
1555 * Creates an an "add tag" entry
1557 * @param array $item
1558 * @param array $data activity data
1560 * @return array with activity data for adding tags
1561 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1562 * @throws \ImagickException
1564 private static function createAddTag($item, $data)
1566 $object = XML::parseString($item['object']);
1567 $target = XML::parseString($item["target"]);
1569 $data['diaspora:guid'] = $item['guid'];
1570 $data['actor'] = $item['author-link'];
1571 $data['target'] = (string)$target->id;
1572 $data['summary'] = BBCode::toPlaintext($item['body']);
1573 $data['object'] = ['id' => (string)$object->id, 'type' => 'tag', 'name' => (string)$object->title, 'content' => (string)$object->content];
1579 * Creates an announce object entry
1581 * @param array $item
1582 * @param array $data activity data
1584 * @return array with activity data
1585 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1586 * @throws \ImagickException
1588 private static function createAnnounce($item, $data)
1590 $orig_body = $item['body'];
1591 $announce = self::getAnnounceArray($item);
1592 if (empty($announce)) {
1593 $data['type'] = 'Create';
1594 $data['object'] = self::createNote($item);
1598 if (empty($announce['comment'])) {
1599 // Pure announce, without a quote
1600 $data['type'] = 'Announce';
1601 $data['object'] = $announce['object']['uri'];
1606 $data['type'] = 'Create';
1607 $item['body'] = $announce['comment'] . "\n" . $announce['object']['plink'];
1608 $data['object'] = self::createNote($item);
1610 /// @todo Finally descide how to implement this in AP. This is a possible way:
1611 $data['object']['attachment'][] = self::createNote($announce['object']);
1613 $data['object']['source']['content'] = $orig_body;
1618 * Return announce related data if the item is an annunce
1620 * @param array $item
1624 public static function getAnnounceArray($item)
1626 $reshared = Item::getShareArray($item);
1627 if (empty($reshared['guid'])) {
1631 $reshared_item = Item::selectFirst([], ['guid' => $reshared['guid']]);
1632 if (!DBA::isResult($reshared_item)) {
1636 if (!in_array($reshared_item['network'], [Protocol::ACTIVITYPUB, Protocol::DFRN])) {
1640 $profile = APContact::getByURL($reshared_item['author-link'], false);
1641 if (empty($profile)) {
1645 return ['object' => $reshared_item, 'actor' => $profile, 'comment' => $reshared['comment']];
1649 * Checks if the provided item array is an announce
1651 * @param array $item
1655 public static function isAnnounce($item)
1657 if (!empty($item['verb']) && ($item['verb'] == Activity::ANNOUNCE)) {
1661 $announce = self::getAnnounceArray($item);
1662 if (empty($announce)) {
1666 return empty($announce['comment']);
1670 * Creates an activity id for a given contact id
1672 * @param integer $cid Contact ID of target
1674 * @return bool|string activity id
1676 public static function activityIDFromContact($cid)
1678 $contact = DBA::selectFirst('contact', ['uid', 'id', 'created'], ['id' => $cid]);
1679 if (!DBA::isResult($contact)) {
1683 $hash = hash('ripemd128', $contact['uid'].'-'.$contact['id'].'-'.$contact['created']);
1684 $uuid = substr($hash, 0, 8). '-' . substr($hash, 8, 4) . '-' . substr($hash, 12, 4) . '-' . substr($hash, 16, 4) . '-' . substr($hash, 20, 12);
1685 return DI::baseUrl() . '/activity/' . $uuid;
1689 * Transmits a contact suggestion to a given inbox
1691 * @param integer $uid User ID
1692 * @param string $inbox Target inbox
1693 * @param integer $suggestion_id Suggestion ID
1695 * @return boolean was the transmission successful?
1696 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1698 public static function sendContactSuggestion($uid, $inbox, $suggestion_id)
1700 $owner = User::getOwnerDataById($uid);
1702 $suggestion = DI::fsuggest()->getById($suggestion_id);
1704 $data = ['@context' => ActivityPub::CONTEXT,
1705 'id' => DI::baseUrl() . '/activity/' . System::createGUID(),
1706 'type' => 'Announce',
1707 'actor' => $owner['url'],
1708 'object' => $suggestion->url,
1709 'content' => $suggestion->note,
1710 'instrument' => self::getService(),
1711 'to' => [ActivityPub::PUBLIC_COLLECTION],
1714 $signed = LDSignature::sign($data, $owner);
1716 Logger::log('Deliver profile deletion for user ' . $uid . ' to ' . $inbox . ' via ActivityPub', Logger::DEBUG);
1717 return HTTPSignature::transmit($signed, $inbox, $uid);
1721 * Transmits a profile relocation to a given inbox
1723 * @param integer $uid User ID
1724 * @param string $inbox Target inbox
1726 * @return boolean was the transmission successful?
1727 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1729 public static function sendProfileRelocation($uid, $inbox)
1731 $owner = User::getOwnerDataById($uid);
1733 $data = ['@context' => ActivityPub::CONTEXT,
1734 'id' => DI::baseUrl() . '/activity/' . System::createGUID(),
1735 'type' => 'dfrn:relocate',
1736 'actor' => $owner['url'],
1737 'object' => $owner['url'],
1738 'published' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
1739 'instrument' => self::getService(),
1740 'to' => [ActivityPub::PUBLIC_COLLECTION],
1743 $signed = LDSignature::sign($data, $owner);
1745 Logger::log('Deliver profile relocation for user ' . $uid . ' to ' . $inbox . ' via ActivityPub', Logger::DEBUG);
1746 return HTTPSignature::transmit($signed, $inbox, $uid);
1750 * Transmits a profile deletion to a given inbox
1752 * @param integer $uid User ID
1753 * @param string $inbox Target inbox
1755 * @return boolean was the transmission successful?
1756 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1758 public static function sendProfileDeletion($uid, $inbox)
1760 $owner = User::getOwnerDataById($uid);
1762 if (empty($owner)) {
1763 Logger::error('No owner data found, the deletion message cannot be processed.', ['user' => $uid]);
1767 if (empty($owner['uprvkey'])) {
1768 Logger::error('No private key for owner found, the deletion message cannot be processed.', ['user' => $uid]);
1772 $data = ['@context' => ActivityPub::CONTEXT,
1773 'id' => DI::baseUrl() . '/activity/' . System::createGUID(),
1775 'actor' => $owner['url'],
1776 'object' => $owner['url'],
1777 'published' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
1778 'instrument' => self::getService(),
1779 'to' => [ActivityPub::PUBLIC_COLLECTION],
1782 $signed = LDSignature::sign($data, $owner);
1784 Logger::log('Deliver profile deletion for user ' . $uid . ' to ' . $inbox . ' via ActivityPub', Logger::DEBUG);
1785 return HTTPSignature::transmit($signed, $inbox, $uid);
1789 * Transmits a profile change to a given inbox
1791 * @param integer $uid User ID
1792 * @param string $inbox Target inbox
1794 * @return boolean was the transmission successful?
1795 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1796 * @throws \ImagickException
1798 public static function sendProfileUpdate($uid, $inbox)
1800 $owner = User::getOwnerDataById($uid);
1801 $profile = APContact::getByURL($owner['url']);
1803 $data = ['@context' => ActivityPub::CONTEXT,
1804 'id' => DI::baseUrl() . '/activity/' . System::createGUID(),
1806 'actor' => $owner['url'],
1807 'object' => self::getProfile($uid),
1808 'published' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
1809 'instrument' => self::getService(),
1810 'to' => [$profile['followers']],
1813 $signed = LDSignature::sign($data, $owner);
1815 Logger::log('Deliver profile update for user ' . $uid . ' to ' . $inbox . ' via ActivityPub', Logger::DEBUG);
1816 return HTTPSignature::transmit($signed, $inbox, $uid);
1820 * Transmits a given activity to a target
1822 * @param string $activity Type name
1823 * @param string $target Target profile
1824 * @param integer $uid User ID
1826 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1827 * @throws \ImagickException
1828 * @throws \Exception
1830 public static function sendActivity($activity, $target, $uid, $id = '')
1832 $profile = APContact::getByURL($target);
1833 if (empty($profile['inbox'])) {
1834 Logger::warning('No inbox found for target', ['target' => $target, 'profile' => $profile]);
1838 $owner = User::getOwnerDataById($uid);
1841 $id = DI::baseUrl() . '/activity/' . System::createGUID();
1844 $data = ['@context' => ActivityPub::CONTEXT,
1846 'type' => $activity,
1847 'actor' => $owner['url'],
1848 'object' => $profile['url'],
1849 'instrument' => self::getService(),
1850 'to' => [$profile['url']]];
1852 Logger::log('Sending activity ' . $activity . ' to ' . $target . ' for user ' . $uid, Logger::DEBUG);
1854 $signed = LDSignature::sign($data, $owner);
1855 return HTTPSignature::transmit($signed, $profile['inbox'], $uid);
1859 * Transmits a "follow object" activity to a target
1860 * This is a preparation for sending automated "follow" requests when receiving "Announce" messages
1862 * @param string $object Object URL
1863 * @param string $target Target profile
1864 * @param integer $uid User ID
1866 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1867 * @throws \ImagickException
1868 * @throws \Exception
1870 public static function sendFollowObject($object, $target, $uid = 0)
1872 $profile = APContact::getByURL($target);
1873 if (empty($profile['inbox'])) {
1874 Logger::warning('No inbox found for target', ['target' => $target, 'profile' => $profile]);
1879 // Fetch the list of administrators
1880 $admin_mail = explode(',', str_replace(' ', '', DI::config()->get('config', 'admin_email')));
1882 // We need to use some user as a sender. It doesn't care who it will send. We will use an administrator account.
1883 $condition = ['verified' => true, 'blocked' => false, 'account_removed' => false, 'account_expired' => false, 'email' => $admin_mail];
1884 $first_user = DBA::selectFirst('user', ['uid'], $condition);
1885 $uid = $first_user['uid'];
1888 $condition = ['verb' => Activity::FOLLOW, 'uid' => 0, 'parent-uri' => $object,
1889 'author-id' => Contact::getPublicIdByUserId($uid)];
1890 if (Item::exists($condition)) {
1891 Logger::log('Follow for ' . $object . ' for user ' . $uid . ' does already exist.', Logger::DEBUG);
1895 $owner = User::getOwnerDataById($uid);
1897 $data = ['@context' => ActivityPub::CONTEXT,
1898 'id' => DI::baseUrl() . '/activity/' . System::createGUID(),
1900 'actor' => $owner['url'],
1901 'object' => $object,
1902 'instrument' => self::getService(),
1903 'to' => [$profile['url']]];
1905 Logger::log('Sending follow ' . $object . ' to ' . $target . ' for user ' . $uid, Logger::DEBUG);
1907 $signed = LDSignature::sign($data, $owner);
1908 return HTTPSignature::transmit($signed, $profile['inbox'], $uid);
1912 * Transmit a message that the contact request had been accepted
1914 * @param string $target Target profile
1916 * @param integer $uid User ID
1917 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1918 * @throws \ImagickException
1920 public static function sendContactAccept($target, $id, $uid)
1922 $profile = APContact::getByURL($target);
1923 if (empty($profile['inbox'])) {
1924 Logger::warning('No inbox found for target', ['target' => $target, 'profile' => $profile]);
1928 $owner = User::getOwnerDataById($uid);
1929 $data = ['@context' => ActivityPub::CONTEXT,
1930 'id' => DI::baseUrl() . '/activity/' . System::createGUID(),
1932 'actor' => $owner['url'],
1934 'id' => (string)$id,
1936 'actor' => $profile['url'],
1937 'object' => $owner['url']
1939 'instrument' => self::getService(),
1940 'to' => [$profile['url']]];
1942 Logger::debug('Sending accept to ' . $target . ' for user ' . $uid . ' with id ' . $id);
1944 $signed = LDSignature::sign($data, $owner);
1945 HTTPSignature::transmit($signed, $profile['inbox'], $uid);
1949 * Reject a contact request or terminates the contact relation
1951 * @param string $target Target profile
1953 * @param integer $uid User ID
1954 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1955 * @throws \ImagickException
1957 public static function sendContactReject($target, $id, $uid)
1959 $profile = APContact::getByURL($target);
1960 if (empty($profile['inbox'])) {
1961 Logger::warning('No inbox found for target', ['target' => $target, 'profile' => $profile]);
1965 $owner = User::getOwnerDataById($uid);
1966 $data = ['@context' => ActivityPub::CONTEXT,
1967 'id' => DI::baseUrl() . '/activity/' . System::createGUID(),
1969 'actor' => $owner['url'],
1971 'id' => (string)$id,
1973 'actor' => $profile['url'],
1974 'object' => $owner['url']
1976 'instrument' => self::getService(),
1977 'to' => [$profile['url']]];
1979 Logger::debug('Sending reject to ' . $target . ' for user ' . $uid . ' with id ' . $id);
1981 $signed = LDSignature::sign($data, $owner);
1982 HTTPSignature::transmit($signed, $profile['inbox'], $uid);
1986 * Transmits a message that we don't want to follow this contact anymore
1988 * @param string $target Target profile
1989 * @param integer $uid User ID
1990 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1991 * @throws \ImagickException
1992 * @throws \Exception
1993 * @return bool success
1995 public static function sendContactUndo($target, $cid, $uid)
1997 $profile = APContact::getByURL($target);
1998 if (empty($profile['inbox'])) {
1999 Logger::warning('No inbox found for target', ['target' => $target, 'profile' => $profile]);
2003 $object_id = self::activityIDFromContact($cid);
2004 if (empty($object_id)) {
2008 $id = DI::baseUrl() . '/activity/' . System::createGUID();
2010 $owner = User::getOwnerDataById($uid);
2011 $data = ['@context' => ActivityPub::CONTEXT,
2014 'actor' => $owner['url'],
2015 'object' => ['id' => $object_id, 'type' => 'Follow',
2016 'actor' => $owner['url'],
2017 'object' => $profile['url']],
2018 'instrument' => self::getService(),
2019 'to' => [$profile['url']]];
2021 Logger::log('Sending undo to ' . $target . ' for user ' . $uid . ' with id ' . $id, Logger::DEBUG);
2023 $signed = LDSignature::sign($data, $owner);
2024 return HTTPSignature::transmit($signed, $profile['inbox'], $uid);
2027 private static function prependMentions($body, int $uriid, string $authorLink)
2031 foreach (Tag::getByURIId($uriid, [Tag::IMPLICIT_MENTION]) as $tag) {
2032 $profile = Contact::getByURL($tag['url'], false, ['addr', 'contact-type', 'nick']);
2033 if (!empty($profile['addr'])
2034 && $profile['contact-type'] != Contact::TYPE_COMMUNITY
2035 && !strstr($body, $profile['addr'])
2036 && !strstr($body, $tag['url'])
2037 && $tag['url'] !== $authorLink
2039 $mentions[] = '@[url=' . $tag['url'] . ']' . $profile['nick'] . '[/url]';
2043 $mentions[] = $body;
2045 return implode(' ', $mentions);