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` = ?)",
72 'Application', 0, 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 DBA::update('contact', ['rel' => Contact::FRIEND], ['id' => $contact['id']]);
129 * Unsubscribe from a relay
131 * @param string $url Subscribe actor url
132 * @param bool $force Set the relay status as non follower even if unsubscribe hadn't worked
133 * @return bool success
135 public static function sendRelayUndoFollow(string $url, bool $force = false)
137 $contact = Contact::getByURL($url);
138 if (empty($contact)) {
142 $success = self::sendContactUndo($url, $contact['id'], 0);
143 if ($success || $force) {
144 DBA::update('contact', ['rel' => Contact::NOTHING], ['id' => $contact['id']]);
151 * Collects a list of contacts of the given owner
153 * @param array $owner Owner array
154 * @param int|array $rel The relevant value(s) contact.rel should match
155 * @param string $module The name of the relevant AP endpoint module (followers|following)
156 * @param integer $page Page number
158 * @return array of owners
161 public static function getContacts($owner, $rel, $module, $page = null)
165 'uid' => $owner['uid'],
173 $condition = DBA::buildCondition($parameters);
175 $sql = "SELECT COUNT(*) as `count`
177 JOIN `apcontact` ON `apcontact`.`url` = `contact`.`url`
180 $contacts = DBA::fetchFirst($sql, ...$parameters);
182 $modulePath = '/' . $module . '/';
184 $data = ['@context' => ActivityPub::CONTEXT];
185 $data['id'] = DI::baseUrl() . $modulePath . $owner['nickname'];
186 $data['type'] = 'OrderedCollection';
187 $data['totalItems'] = $contacts['count'];
189 // When we hide our friends we will only show the pure number but don't allow more.
190 $profile = Profile::getByUID($owner['uid']);
191 if (!empty($profile['hide-friends'])) {
196 $data['first'] = DI::baseUrl() . $modulePath . $owner['nickname'] . '?page=1';
198 $data['type'] = 'OrderedCollectionPage';
201 $sql = "SELECT `contact`.`url`
203 JOIN `apcontact` ON `apcontact`.`url` = `contact`.`url`
207 $parameters[] = ($page - 1) * 100;
210 $contacts = DBA::p($sql, ...$parameters);
211 while ($contact = DBA::fetch($contacts)) {
212 $list[] = $contact['url'];
214 DBA::close($contacts);
217 $data['next'] = DI::baseUrl() . $modulePath . $owner['nickname'] . '?page=' . ($page + 1);
220 $data['partOf'] = DI::baseUrl() . $modulePath . $owner['nickname'];
222 $data['orderedItems'] = $list;
229 * Public posts for the given owner
231 * @param array $owner Owner array
232 * @param integer $page Page number
233 * @param string $requester URL of requesting account
235 * @return array of posts
236 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
237 * @throws \ImagickException
239 public static function getOutbox($owner, $page = null, $requester = '')
241 $public_contact = Contact::getIdForURL($owner['url']);
242 $condition = ['uid' => 0, 'contact-id' => $public_contact,
243 'private' => [Item::PUBLIC, Item::UNLISTED]];
245 if (!empty($requester)) {
246 $requester_id = Contact::getIdForURL($requester, $owner['uid']);
247 if (!empty($requester_id)) {
248 $permissionSets = DI::permissionSet()->selectByContactId($requester_id, $owner['uid']);
249 if (!empty($permissionSets)) {
250 $condition = ['uid' => $owner['uid'], 'origin' => true,
251 'psid' => array_merge($permissionSets->column('id'),
252 [DI::permissionSet()->getIdFromACL($owner['uid'], '', '', '', '')])];
257 $condition = array_merge($condition,
258 ['author-id' => $public_contact,
259 'gravity' => [GRAVITY_PARENT, GRAVITY_COMMENT],
260 'deleted' => false, 'visible' => true, 'moderated' => false]);
262 $count = DBA::count('item', $condition);
264 $data = ['@context' => ActivityPub::CONTEXT];
265 $data['id'] = DI::baseUrl() . '/outbox/' . $owner['nickname'];
266 $data['type'] = 'OrderedCollection';
267 $data['totalItems'] = $count;
270 $data['first'] = DI::baseUrl() . '/outbox/' . $owner['nickname'] . '?page=1';
272 $data['type'] = 'OrderedCollectionPage';
275 $condition['parent-network'] = Protocol::NATIVE_SUPPORT;
277 $items = Item::select(['id'], $condition, ['limit' => [($page - 1) * 20, 20], 'order' => ['created' => true]]);
278 while ($item = Item::fetch($items)) {
279 $activity = self::createActivityFromItem($item['id'], true);
280 $activity['type'] = $activity['type'] == 'Update' ? 'Create' : $activity['type'];
282 // Only list "Create" activity objects here, no reshares
283 if (!empty($activity['object']) && ($activity['type'] == 'Create')) {
284 $list[] = $activity['object'];
289 $data['next'] = DI::baseUrl() . '/outbox/' . $owner['nickname'] . '?page=' . ($page + 1);
292 $data['partOf'] = DI::baseUrl() . '/outbox/' . $owner['nickname'];
294 $data['orderedItems'] = $list;
301 * Return the service array containing information the used software and it's url
303 * @return array with service data
305 private static function getService()
307 return ['type' => 'Service',
308 'name' => FRIENDICA_PLATFORM . " '" . FRIENDICA_CODENAME . "' " . FRIENDICA_VERSION . '-' . DB_UPDATE_VERSION,
309 'url' => DI::baseUrl()->get()];
313 * Return the ActivityPub profile of the given user
315 * @param integer $uid User ID
316 * @return array with profile data
317 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
319 public static function getProfile($uid)
322 $condition = ['uid' => $uid, 'blocked' => false, 'account_expired' => false,
323 'account_removed' => false, 'verified' => true];
324 $fields = ['guid', 'nickname', 'pubkey', 'account-type', 'page-flags'];
325 $user = DBA::selectFirst('user', $fields, $condition);
326 if (!DBA::isResult($user)) {
330 $fields = ['locality', 'region', 'country-name'];
331 $profile = DBA::selectFirst('profile', $fields, ['uid' => $uid]);
332 if (!DBA::isResult($profile)) {
336 $fields = ['name', 'url', 'location', 'about', 'avatar', 'photo'];
337 $contact = DBA::selectFirst('contact', $fields, ['uid' => $uid, 'self' => true]);
338 if (!DBA::isResult($contact)) {
342 $contact = User::getSystemAccount();
343 $user = ['guid' => '', 'nickname' => $contact['nick'], 'pubkey' => $contact['pubkey'],
344 'account-type' => $contact['contact-type'], 'page-flags' => User::PAGE_FLAGS_NORMAL];
345 $profile = ['locality' => '', 'region' => '', 'country-name' => ''];
348 $data = ['@context' => ActivityPub::CONTEXT];
349 $data['id'] = $contact['url'];
351 if (!empty($user['guid'])) {
352 $data['diaspora:guid'] = $user['guid'];
355 $data['type'] = ActivityPub::ACCOUNT_TYPES[$user['account-type']];
358 $data['following'] = DI::baseUrl() . '/following/' . $user['nickname'];
359 $data['followers'] = DI::baseUrl() . '/followers/' . $user['nickname'];
360 $data['inbox'] = DI::baseUrl() . '/inbox/' . $user['nickname'];
361 $data['outbox'] = DI::baseUrl() . '/outbox/' . $user['nickname'];
363 $data['inbox'] = DI::baseUrl() . '/friendica/inbox';
366 $data['preferredUsername'] = $user['nickname'];
367 $data['name'] = $contact['name'];
369 if (!empty($profile['country-name'] . $profile['region'] . $profile['locality'])) {
370 $data['vcard:hasAddress'] = ['@type' => 'vcard:Home', 'vcard:country-name' => $profile['country-name'],
371 'vcard:region' => $profile['region'], 'vcard:locality' => $profile['locality']];
374 if (!empty($contact['about'])) {
375 $data['summary'] = BBCode::convert($contact['about'], false);
378 $data['url'] = $contact['url'];
379 $data['manuallyApprovesFollowers'] = in_array($user['page-flags'], [User::PAGE_FLAGS_NORMAL, User::PAGE_FLAGS_PRVGROUP]);
380 $data['publicKey'] = ['id' => $contact['url'] . '#main-key',
381 'owner' => $contact['url'],
382 'publicKeyPem' => $user['pubkey']];
383 $data['endpoints'] = ['sharedInbox' => DI::baseUrl() . '/inbox'];
384 $data['icon'] = ['type' => 'Image',
385 'url' => $contact['photo']];
387 $data['generator'] = self::getService();
389 // tags: https://kitty.town/@inmysocks/100656097926961126.json
394 * @param string $username
396 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
398 public static function getDeletedUser($username)
401 '@context' => ActivityPub::CONTEXT,
402 'id' => DI::baseUrl() . '/profile/' . $username,
403 'type' => 'Tombstone',
404 'published' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
405 'updated' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
406 'deleted' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
411 * Returns an array with permissions of a given item array
415 * @return array with permissions
416 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
417 * @throws \ImagickException
419 private static function fetchPermissionBlockFromConversation($item)
421 if (empty($item['thr-parent'])) {
425 $condition = ['item-uri' => $item['thr-parent'], 'protocol' => Conversation::PARCEL_ACTIVITYPUB];
426 $conversation = DBA::selectFirst('conversation', ['source'], $condition);
427 if (!DBA::isResult($conversation)) {
431 $activity = json_decode($conversation['source'], true);
433 $actor = JsonLD::fetchElement($activity, 'actor', 'id');
434 if (!empty($actor)) {
435 $permissions['to'][] = $actor;
436 $profile = APContact::getByURL($actor);
441 $item_profile = APContact::getByURL($item['author-link']);
442 $exclude[] = $item['author-link'];
444 if ($item['gravity'] == GRAVITY_PARENT) {
445 $exclude[] = $item['owner-link'];
448 foreach (['to', 'cc', 'bto', 'bcc'] as $element) {
449 if (empty($activity[$element])) {
452 if (is_string($activity[$element])) {
453 $activity[$element] = [$activity[$element]];
456 foreach ($activity[$element] as $receiver) {
457 if (empty($receiver)) {
461 if (!empty($profile['followers']) && $receiver == $profile['followers'] && !empty($item_profile['followers'])) {
462 $permissions[$element][] = $item_profile['followers'];
463 } elseif (!in_array($receiver, $exclude)) {
464 $permissions[$element][] = $receiver;
472 * Check if the given item id is from ActivityPub
474 * @param integer $item_id
475 * @return boolean "true" if the post is from ActivityPub
477 private static function isAPPost(int $item_id)
479 if (empty($item_id)) {
483 return Item::exists(['id' => $item_id, 'network' => Protocol::ACTIVITYPUB]);
487 * Creates an array of permissions from an item thread
489 * @param array $item Item array
490 * @param boolean $blindcopy addressing via "bcc" or "cc"?
491 * @param integer $last_id Last item id for adding receivers
492 * @param boolean $forum_mode "true" means that we are sending content to a forum
494 * @return array with permission data
495 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
496 * @throws \ImagickException
498 private static function createPermissionBlockForItem($item, $blindcopy, $last_id = 0, $forum_mode = false)
501 $last_id = $item['id'];
506 // Check if we should always deliver our stuff via BCC
507 if (!empty($item['uid'])) {
508 $profile = User::getOwnerDataById($item['uid']);
509 if (!empty($profile)) {
510 $always_bcc = $profile['hide-friends'];
514 if (DI::config()->get('system', 'ap_always_bcc')) {
518 if (self::isAnnounce($item) || DI::config()->get('debug', 'total_ap_delivery') || self::isAPPost($last_id)) {
519 // Will be activated in a later step
520 $networks = Protocol::FEDERATED;
522 // For now only send to these contacts:
523 $networks = [Protocol::ACTIVITYPUB, Protocol::OSTATUS];
526 $data = ['to' => [], 'cc' => [], 'bcc' => []];
528 if ($item['gravity'] == GRAVITY_PARENT) {
529 $actor_profile = APContact::getByURL($item['owner-link']);
531 $actor_profile = APContact::getByURL($item['author-link']);
534 $terms = Tag::getByURIId($item['uri-id'], [Tag::MENTION, Tag::IMPLICIT_MENTION, Tag::EXCLUSIVE_MENTION]);
536 if ($item['private'] != Item::PRIVATE) {
537 // Directly mention the original author upon a quoted reshare.
538 // Else just ensure that the original author receives the reshare.
539 $announce = self::getAnnounceArray($item);
540 if (!empty($announce['comment'])) {
541 $data['to'][] = $announce['actor']['url'];
542 } elseif (!empty($announce)) {
543 $data['cc'][] = $announce['actor']['url'];
546 $data = array_merge($data, self::fetchPermissionBlockFromConversation($item));
548 // Check if the item is completely public or unlisted
549 if ($item['private'] == Item::PUBLIC) {
550 $data['to'][] = ActivityPub::PUBLIC_COLLECTION;
552 $data['cc'][] = ActivityPub::PUBLIC_COLLECTION;
555 foreach ($terms as $term) {
556 $profile = APContact::getByURL($term['url'], false);
557 if (!empty($profile)) {
558 $data['to'][] = $profile['url'];
562 $receiver_list = Item::enumeratePermissions($item, true);
564 foreach ($terms as $term) {
565 $cid = Contact::getIdForURL($term['url'], $item['uid']);
566 if (!empty($cid) && in_array($cid, $receiver_list)) {
567 $contact = DBA::selectFirst('contact', ['url', 'network', 'protocol'], ['id' => $cid]);
568 if (!DBA::isResult($contact) || (!in_array($contact['network'], $networks) && ($contact['protocol'] != Protocol::ACTIVITYPUB))) {
572 if (!empty($profile = APContact::getByURL($contact['url'], false))) {
573 $data['to'][] = $profile['url'];
578 foreach ($receiver_list as $receiver) {
579 $contact = DBA::selectFirst('contact', ['url', 'hidden', 'network', 'protocol'], ['id' => $receiver]);
580 if (!DBA::isResult($contact) || (!in_array($contact['network'], $networks) && ($contact['protocol'] != Protocol::ACTIVITYPUB))) {
584 if (!empty($profile = APContact::getByURL($contact['url'], false))) {
585 if ($contact['hidden'] || $always_bcc) {
586 $data['bcc'][] = $profile['url'];
588 $data['cc'][] = $profile['url'];
594 if (!empty($item['parent'])) {
595 $parents = Item::select(['id', 'author-link', 'owner-link', 'gravity', 'uri'], ['parent' => $item['parent']]);
596 while ($parent = Item::fetch($parents)) {
597 if ($parent['gravity'] == GRAVITY_PARENT) {
598 $profile = APContact::getByURL($parent['owner-link'], false);
599 if (!empty($profile)) {
600 if ($item['gravity'] != GRAVITY_PARENT) {
601 // Comments to forums are directed to the forum
602 // But comments to forums aren't directed to the followers collection
603 // This rule is only valid when the actor isn't the forum.
604 // The forum needs to transmit their content to their followers.
605 if (($profile['type'] == 'Group') && ($profile['url'] != $actor_profile['url'])) {
606 $data['to'][] = $profile['url'];
608 $data['cc'][] = $profile['url'];
609 if (($item['private'] != Item::PRIVATE) && !empty($actor_profile['followers'])) {
610 $data['cc'][] = $actor_profile['followers'];
614 // Public thread parent post always are directed to the followers
615 if (($item['private'] != Item::PRIVATE) && !$forum_mode) {
616 $data['cc'][] = $actor_profile['followers'];
622 // Don't include data from future posts
623 if ($parent['id'] >= $last_id) {
627 $profile = APContact::getByURL($parent['author-link'], false);
628 if (!empty($profile)) {
629 if (($profile['type'] == 'Group') || ($parent['uri'] == $item['thr-parent'])) {
630 $data['to'][] = $profile['url'];
632 $data['cc'][] = $profile['url'];
636 DBA::close($parents);
639 $data['to'] = array_unique($data['to']);
640 $data['cc'] = array_unique($data['cc']);
641 $data['bcc'] = array_unique($data['bcc']);
643 if (($key = array_search($item['author-link'], $data['to'])) !== false) {
644 unset($data['to'][$key]);
647 if (($key = array_search($item['author-link'], $data['cc'])) !== false) {
648 unset($data['cc'][$key]);
651 if (($key = array_search($item['author-link'], $data['bcc'])) !== false) {
652 unset($data['bcc'][$key]);
655 foreach ($data['to'] as $to) {
656 if (($key = array_search($to, $data['cc'])) !== false) {
657 unset($data['cc'][$key]);
660 if (($key = array_search($to, $data['bcc'])) !== false) {
661 unset($data['bcc'][$key]);
665 foreach ($data['cc'] as $cc) {
666 if (($key = array_search($cc, $data['bcc'])) !== false) {
667 unset($data['bcc'][$key]);
671 $receivers = ['to' => array_values($data['to']), 'cc' => array_values($data['cc']), 'bcc' => array_values($data['bcc'])];
674 unset($receivers['bcc']);
681 * Check if an inbox is archived
683 * @param string $url Inbox url
685 * @return boolean "true" if inbox is archived
687 public static function archivedInbox($url)
689 return DBA::exists('inbox-status', ['url' => $url, 'archive' => true]);
693 * Fetches a list of inboxes of followers of a given user
695 * @param integer $uid User ID
696 * @param boolean $personal fetch personal inboxes
697 * @param boolean $all_ap Retrieve all AP enabled inboxes
699 * @return array of follower inboxes
700 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
701 * @throws \ImagickException
703 public static function fetchTargetInboxesforUser($uid, $personal = false, bool $all_ap = false)
709 if (!empty($item['uid'])) {
710 $profile = User::getOwnerDataById($item['uid']);
711 if (!empty($profile)) {
712 $isforum = $profile['account-type'] == User::ACCOUNT_TYPE_COMMUNITY;
716 if (DI::config()->get('debug', 'total_ap_delivery') || $all_ap) {
717 // Will be activated in a later step
718 $networks = Protocol::FEDERATED;
720 // For now only send to these contacts:
721 $networks = [Protocol::ACTIVITYPUB, Protocol::OSTATUS];
724 $condition = ['uid' => $uid, 'archive' => false, 'pending' => false, 'blocked' => false];
727 $condition['rel'] = [Contact::FOLLOWER, Contact::FRIEND];
730 $contacts = DBA::select('contact', ['id', 'url', 'network', 'protocol'], $condition);
731 while ($contact = DBA::fetch($contacts)) {
732 if (Contact::isLocal($contact['url'])) {
736 if (!in_array($contact['network'], $networks) && ($contact['protocol'] != Protocol::ACTIVITYPUB)) {
740 if ($isforum && ($contact['network'] == Protocol::DFRN)) {
744 if (Network::isUrlBlocked($contact['url'])) {
748 $profile = APContact::getByURL($contact['url'], false);
749 if (!empty($profile)) {
750 if (empty($profile['sharedinbox']) || $personal) {
751 $target = $profile['inbox'];
753 $target = $profile['sharedinbox'];
755 if (!self::archivedInbox($target)) {
756 $inboxes[$target][] = $contact['id'];
760 DBA::close($contacts);
766 * Fetches an array of inboxes for the given item and user
768 * @param array $item Item array
769 * @param integer $uid User ID
770 * @param boolean $personal fetch personal inboxes
771 * @param integer $last_id Last item id for adding receivers
772 * @param boolean $forum_mode "true" means that we are sending content to a forum
773 * @return array with inboxes
774 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
775 * @throws \ImagickException
777 public static function fetchTargetInboxes($item, $uid, $personal = false, $last_id = 0, $forum_mode = false)
779 $permissions = self::createPermissionBlockForItem($item, true, $last_id, $forum_mode);
780 if (empty($permissions)) {
786 if ($item['gravity'] == GRAVITY_ACTIVITY) {
787 $item_profile = APContact::getByURL($item['author-link'], false);
789 $item_profile = APContact::getByURL($item['owner-link'], false);
792 if (empty($item_profile)) {
796 $profile_uid = User::getIdForURL($item_profile['url']);
798 foreach (['to', 'cc', 'bto', 'bcc'] as $element) {
799 if (empty($permissions[$element])) {
803 $blindcopy = in_array($element, ['bto', 'bcc']);
805 foreach ($permissions[$element] as $receiver) {
806 if (empty($receiver) || Network::isUrlBlocked($receiver)) {
810 if ($item_profile && ($receiver == $item_profile['followers']) && ($uid == $profile_uid)) {
811 $inboxes = array_merge($inboxes, self::fetchTargetInboxesforUser($uid, $personal, self::isAPPost($last_id)));
813 if (Contact::isLocal($receiver)) {
817 $profile = APContact::getByURL($receiver, false);
818 if (!empty($profile)) {
819 $contact = Contact::getByURLForUser($receiver, $uid, false, ['id']);
821 if (empty($profile['sharedinbox']) || $personal || $blindcopy) {
822 $target = $profile['inbox'];
824 $target = $profile['sharedinbox'];
826 if (!self::archivedInbox($target)) {
827 $inboxes[$target][] = $contact['id'] ?? 0;
838 * Creates an array in the structure of the item table for a given mail id
840 * @param integer $mail_id
845 public static function ItemArrayFromMail($mail_id)
847 $mail = DBA::selectFirst('mail', [], ['id' => $mail_id]);
848 if (!DBA::isResult($mail)) {
852 $mail['uri-id'] = ItemURI::insert(['uri' => $mail['uri'], 'guid' => $mail['guid']]);
854 $reply = DBA::selectFirst('mail', ['uri'], ['parent-uri' => $mail['parent-uri'], 'reply' => false]);
856 // Making the post more compatible for Mastodon by:
857 // - Making it a note and not an article (no title)
858 // - Moving the title into the "summary" field that is used as a "content warning"
859 $mail['body'] = '[abstract]' . $mail['title'] . "[/abstract]\n" . $mail['body'];
862 $mail['author-link'] = $mail['owner-link'] = $mail['from-url'];
863 $mail['allow_cid'] = '<'.$mail['contact-id'].'>';
864 $mail['allow_gid'] = '';
865 $mail['deny_cid'] = '';
866 $mail['deny_gid'] = '';
867 $mail['private'] = true;
868 $mail['deleted'] = false;
869 $mail['edited'] = $mail['created'];
870 $mail['plink'] = $mail['uri'];
871 $mail['thr-parent'] = $reply['uri'];
872 $mail['gravity'] = ($mail['reply'] ? GRAVITY_COMMENT: GRAVITY_PARENT);
874 $mail['event-type'] = '';
882 * Creates an activity array for a given mail id
884 * @param integer $mail_id
885 * @param boolean $object_mode Is the activity item is used inside another object?
887 * @return array of activity
890 public static function createActivityFromMail($mail_id, $object_mode = false)
892 $mail = self::ItemArrayFromMail($mail_id);
896 $object = self::createNote($mail);
899 $data = ['@context' => ActivityPub::CONTEXT];
904 $data['id'] = $mail['uri'] . '/Create';
905 $data['type'] = 'Create';
906 $data['actor'] = $mail['author-link'];
907 $data['published'] = DateTimeFormat::utc($mail['created'] . '+00:00', DateTimeFormat::ATOM);
908 $data['instrument'] = self::getService();
909 $data = array_merge($data, self::createPermissionBlockForItem($mail, true));
911 if (empty($data['to']) && !empty($data['cc'])) {
912 $data['to'] = $data['cc'];
915 if (empty($data['to']) && !empty($data['bcc'])) {
916 $data['to'] = $data['bcc'];
922 $object['to'] = $data['to'];
923 $object['tag'] = [['type' => 'Mention', 'href' => $object['to'][0], 'name' => '']];
925 unset($object['cc']);
926 unset($object['bcc']);
928 $data['directMessage'] = true;
930 $data['object'] = $object;
932 $owner = User::getOwnerDataById($mail['uid']);
934 if (!$object_mode && !empty($owner)) {
935 return LDSignature::sign($data, $owner);
942 * Returns the activity type of a given item
946 * @return string with activity type
947 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
948 * @throws \ImagickException
950 private static function getTypeOfItem($item)
954 // Only check for a reshare, if it is a real reshare and no quoted reshare
955 if (strpos($item['body'], "[share") === 0) {
956 $announce = self::getAnnounceArray($item);
957 $reshared = !empty($announce);
962 } elseif ($item['verb'] == Activity::POST) {
963 if ($item['created'] == $item['edited']) {
968 } elseif ($item['verb'] == Activity::LIKE) {
970 } elseif ($item['verb'] == Activity::DISLIKE) {
972 } elseif ($item['verb'] == Activity::ATTEND) {
974 } elseif ($item['verb'] == Activity::ATTENDNO) {
976 } elseif ($item['verb'] == Activity::ATTENDMAYBE) {
977 $type = 'TentativeAccept';
978 } elseif ($item['verb'] == Activity::FOLLOW) {
980 } elseif ($item['verb'] == Activity::TAG) {
982 } elseif ($item['verb'] == Activity::ANNOUNCE) {
992 * Creates the activity or fetches it from the cache
994 * @param integer $item_id
995 * @param boolean $force Force new cache entry
997 * @return array with the activity
1000 public static function createCachedActivityFromItem($item_id, $force = false)
1002 $cachekey = 'APDelivery:createActivity:' . $item_id;
1005 $data = DI::cache()->get($cachekey);
1006 if (!is_null($data)) {
1011 $data = self::createActivityFromItem($item_id);
1013 DI::cache()->set($cachekey, $data, Duration::QUARTER_HOUR);
1018 * Creates an activity array for a given item id
1020 * @param integer $item_id
1021 * @param boolean $object_mode Is the activity item is used inside another object?
1023 * @return false|array
1024 * @throws \Exception
1026 public static function createActivityFromItem(int $item_id, bool $object_mode = false)
1028 Logger::info('Fetching activity', ['item' => $item_id]);
1029 $item = Item::selectFirst([], ['id' => $item_id, 'parent-network' => Protocol::NATIVE_SUPPORT]);
1030 if (!DBA::isResult($item)) {
1034 // In case of a forum post ensure to return the original post if author and forum are on the same machine
1035 if (!empty($item['forum_mode'])) {
1036 $author = Contact::getById($item['author-id'], ['nurl']);
1037 if (!empty($author['nurl'])) {
1038 $self = Contact::selectFirst(['uid'], ['nurl' => $author['nurl'], 'self' => true]);
1039 if (!empty($self['uid'])) {
1040 $forum_item = Item::selectFirst([], ['uri-id' => $item['uri-id'], 'uid' => $self['uid']]);
1041 if (DBA::isResult($item)) {
1042 $item = $forum_item;
1048 if (empty($item['uri-id'])) {
1049 Logger::warning('Item without uri-id', ['item' => $item]);
1053 $condition = ['item-uri' => $item['uri'], 'protocol' => Conversation::PARCEL_ACTIVITYPUB];
1054 $conversation = DBA::selectFirst('conversation', ['source'], $condition);
1055 if (!$item['origin'] && DBA::isResult($conversation)) {
1056 $data = json_decode($conversation['source'], true);
1057 if (!empty($data['type'])) {
1058 if (in_array($data['type'], ['Create', 'Update'])) {
1060 unset($data['@context']);
1061 unset($data['signature']);
1063 Logger::info('Return stored conversation', ['item' => $item_id]);
1065 } elseif (in_array('as:' . $data['type'], Receiver::CONTENT_TYPES)) {
1066 if (!empty($data['@context'])) {
1067 $context = $data['@context'];
1068 unset($data['@context']);
1070 unset($data['actor']);
1076 $type = self::getTypeOfItem($item);
1078 if (!$object_mode) {
1079 $data = ['@context' => $context ?? ActivityPub::CONTEXT];
1081 if ($item['deleted'] && ($item['gravity'] == GRAVITY_ACTIVITY)) {
1083 } elseif ($item['deleted']) {
1090 if (($item['gravity'] == GRAVITY_ACTIVITY) && ($type != 'Undo')) {
1091 $data['id'] = $item['uri'];
1093 $data['id'] = $item['uri'] . '/' . $type;
1096 $data['type'] = $type;
1098 if (($type != 'Announce') || ($item['gravity'] != GRAVITY_PARENT)) {
1099 $data['actor'] = $item['author-link'];
1101 $data['actor'] = $item['owner-link'];
1104 $data['published'] = DateTimeFormat::utc($item['created'] . '+00:00', DateTimeFormat::ATOM);
1106 $data['instrument'] = self::getService();
1108 $data = array_merge($data, self::createPermissionBlockForItem($item, false));
1110 if (in_array($data['type'], ['Create', 'Update', 'Delete'])) {
1111 $data['object'] = $object ?? self::createNote($item);
1112 } elseif ($data['type'] == 'Add') {
1113 $data = self::createAddTag($item, $data);
1114 } elseif ($data['type'] == 'Announce') {
1115 if ($item['verb'] == ACTIVITY::ANNOUNCE) {
1116 $data['object'] = $item['thr-parent'];
1118 $data = self::createAnnounce($item, $data);
1120 } elseif ($data['type'] == 'Follow') {
1121 $data['object'] = $item['parent-uri'];
1122 } elseif ($data['type'] == 'Undo') {
1123 $data['object'] = self::createActivityFromItem($item_id, true);
1125 $data['diaspora:guid'] = $item['guid'];
1126 if (!empty($item['signed_text'])) {
1127 $data['diaspora:like'] = $item['signed_text'];
1129 $data['object'] = $item['thr-parent'];
1132 if (!empty($item['contact-uid'])) {
1133 $uid = $item['contact-uid'];
1135 $uid = $item['uid'];
1138 $owner = User::getOwnerDataById($uid);
1140 Logger::info('Fetched activity', ['item' => $item_id, 'uid' => $uid]);
1142 // We don't sign if we aren't the actor. This is important for relaying content especially for forums
1143 if (!$object_mode && !empty($owner) && ($data['actor'] == $owner['url'])) {
1144 return LDSignature::sign($data, $owner);
1149 /// @todo Create "conversation" entry
1153 * Creates a location entry for a given item array
1155 * @param array $item
1157 * @return array with location array
1159 private static function createLocation($item)
1161 $location = ['type' => 'Place'];
1163 if (!empty($item['location'])) {
1164 $location['name'] = $item['location'];
1169 if (empty($item['coord'])) {
1170 $coord = Map::getCoordinates($item['location']);
1172 $coords = explode(' ', $item['coord']);
1173 if (count($coords) == 2) {
1174 $coord = ['lat' => $coords[0], 'lon' => $coords[1]];
1178 if (!empty($coord['lat']) && !empty($coord['lon'])) {
1179 $location['latitude'] = $coord['lat'];
1180 $location['longitude'] = $coord['lon'];
1187 * Returns a tag array for a given item array
1189 * @param array $item
1191 * @return array of tags
1192 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1194 private static function createTagList($item)
1198 $terms = Tag::getByURIId($item['uri-id'], [Tag::HASHTAG, Tag::MENTION, Tag::IMPLICIT_MENTION, Tag::EXCLUSIVE_MENTION]);
1199 foreach ($terms as $term) {
1200 if ($term['type'] == Tag::HASHTAG) {
1201 $url = DI::baseUrl() . '/search?tag=' . urlencode($term['name']);
1202 $tags[] = ['type' => 'Hashtag', 'href' => $url, 'name' => '#' . $term['name']];
1204 $contact = Contact::getByURL($term['url'], false, ['addr']);
1205 if (empty($contact)) {
1208 if (!empty($contact['addr'])) {
1209 $mention = '@' . $contact['addr'];
1211 $mention = '@' . $term['url'];
1214 $tags[] = ['type' => 'Mention', 'href' => $term['url'], 'name' => $mention];
1218 $announce = self::getAnnounceArray($item);
1219 // Mention the original author upon commented reshares
1220 if (!empty($announce['comment'])) {
1221 $tags[] = ['type' => 'Mention', 'href' => $announce['actor']['url'], 'name' => '@' . $announce['actor']['addr']];
1228 * Adds attachment data to the JSON document
1230 * @param array $item Data of the item that is to be posted
1231 * @param string $type Object type
1233 * @return array with attachment data
1234 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1236 private static function createAttachmentList($item, $type)
1240 // Currently deactivated, since it creates side effects on Mastodon and Pleroma.
1241 // It will be reactivated, once this cleared.
1243 $attach_data = BBCode::getAttachmentData($item['body']);
1244 if (!empty($attach_data['url'])) {
1245 $attachment = ['type' => 'Page',
1246 'mediaType' => 'text/html',
1247 'url' => $attach_data['url']];
1249 if (!empty($attach_data['title'])) {
1250 $attachment['name'] = $attach_data['title'];
1253 if (!empty($attach_data['description'])) {
1254 $attachment['summary'] = $attach_data['description'];
1257 if (!empty($attach_data['image'])) {
1258 $imgdata = Images::getInfoFromURLCached($attach_data['image']);
1260 $attachment['icon'] = ['type' => 'Image',
1261 'mediaType' => $imgdata['mime'],
1262 'width' => $imgdata[0],
1263 'height' => $imgdata[1],
1264 'url' => $attach_data['image']];
1268 $attachments[] = $attachment;
1271 foreach (Post\Media::getByURIId($item['uri-id'], [Post\Media::DOCUMENT, Post\Media::TORRENT, Post\Media::UNKNOWN]) as $attachment) {
1272 $attachments[] = ['type' => 'Document',
1273 'mediaType' => $attachment['mimetype'],
1274 'url' => $attachment['url'],
1275 'name' => $attachment['description']];
1278 if ($type != 'Note') {
1279 return $attachments;
1282 foreach (Post\Media::getByURIId($item['uri-id'], [Post\Media::AUDIO, Post\Media::IMAGE, Post\Media::VIDEO]) as $attachment) {
1283 $attachments[] = ['type' => 'Document',
1284 'mediaType' => $attachment['mimetype'],
1285 'url' => $attachment['url'],
1286 'name' => $attachment['description']];
1289 return $attachments;
1293 * Callback function to replace a Friendica style mention in a mention that is used on AP
1295 * @param array $match Matching values for the callback
1296 * @return string Replaced mention
1297 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1299 private static function mentionCallback($match)
1301 if (empty($match[1])) {
1305 $data = Contact::getByURL($match[1], false, ['url', 'alias', 'nick']);
1306 if (empty($data['nick'])) {
1310 return '[url=' . ($data['alias'] ?: $data['url']) . ']@' . $data['nick'] . '[/url]';
1314 * Remove image elements since they are added as attachment
1316 * @param string $body
1318 * @return string with removed images
1320 private static function removePictures($body)
1322 // Simplify image codes
1323 $body = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '[img]$3[/img]', $body);
1324 $body = preg_replace("/\[img\=(.*?)\](.*?)\[\/img\]/ism", '[img]$1[/img]', $body);
1326 // Now remove local links
1327 $body = preg_replace_callback(
1328 '/\[url=([^\[\]]*)\]\[img\](.*)\[\/img\]\[\/url\]/Usi',
1330 // We remove the link when it is a link to a local photo page
1331 if (Photo::isLocalPage($match[1])) {
1334 // otherwise we just return the link
1335 return '[url]' . $match[1] . '[/url]';
1340 // Remove all pictures
1341 $body = preg_replace("/\[img\]([^\[\]]*)\[\/img\]/Usi", '', $body);
1347 * Fetches the "context" value for a givem item array from the "conversation" table
1349 * @param array $item
1351 * @return string with context url
1352 * @throws \Exception
1354 private static function fetchContextURLForItem($item)
1356 $conversation = DBA::selectFirst('conversation', ['conversation-href', 'conversation-uri'], ['item-uri' => $item['parent-uri']]);
1357 if (DBA::isResult($conversation) && !empty($conversation['conversation-href'])) {
1358 $context_uri = $conversation['conversation-href'];
1359 } elseif (DBA::isResult($conversation) && !empty($conversation['conversation-uri'])) {
1360 $context_uri = $conversation['conversation-uri'];
1362 $context_uri = $item['parent-uri'] . '#context';
1364 return $context_uri;
1368 * Returns if the post contains sensitive content ("nsfw")
1370 * @param integer $uri_id
1373 * @throws \Exception
1375 private static function isSensitive($uri_id)
1377 return DBA::exists('tag-view', ['uri-id' => $uri_id, 'name' => 'nsfw']);
1381 * Creates event data
1383 * @param array $item
1385 * @return array with the event data
1386 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1388 public static function createEvent($item)
1391 $event['name'] = $item['event-summary'];
1392 $event['content'] = BBCode::convert($item['event-desc'], false, BBCode::ACTIVITYPUB);
1393 $event['startTime'] = DateTimeFormat::utc($item['event-start'] . '+00:00', DateTimeFormat::ATOM);
1395 if (!$item['event-nofinish']) {
1396 $event['endTime'] = DateTimeFormat::utc($item['event-finish'] . '+00:00', DateTimeFormat::ATOM);
1399 if (!empty($item['event-location'])) {
1400 $item['location'] = $item['event-location'];
1401 $event['location'] = self::createLocation($item);
1408 * Creates a note/article object array
1410 * @param array $item
1412 * @return array with the object data
1413 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1414 * @throws \ImagickException
1416 public static function createNote($item)
1422 if ($item['event-type'] == 'event') {
1424 } elseif (!empty($item['title'])) {
1430 if ($item['deleted']) {
1431 $type = 'Tombstone';
1435 $data['id'] = $item['uri'];
1436 $data['type'] = $type;
1438 if ($item['deleted']) {
1442 $data['summary'] = BBCode::toPlaintext(BBCode::getAbstract($item['body'], Protocol::ACTIVITYPUB));
1444 if ($item['uri'] != $item['thr-parent']) {
1445 $data['inReplyTo'] = $item['thr-parent'];
1447 $data['inReplyTo'] = null;
1450 $data['diaspora:guid'] = $item['guid'];
1451 $data['published'] = DateTimeFormat::utc($item['created'] . '+00:00', DateTimeFormat::ATOM);
1453 if ($item['created'] != $item['edited']) {
1454 $data['updated'] = DateTimeFormat::utc($item['edited'] . '+00:00', DateTimeFormat::ATOM);
1457 $data['url'] = $item['plink'];
1458 $data['attributedTo'] = $item['author-link'];
1459 $data['sensitive'] = self::isSensitive($item['uri-id']);
1460 $data['context'] = self::fetchContextURLForItem($item);
1462 if (!empty($item['title'])) {
1463 $data['name'] = BBCode::toPlaintext($item['title'], false);
1466 $permission_block = self::createPermissionBlockForItem($item, false);
1468 $body = $item['body'];
1470 if ($type == 'Note') {
1471 $body = $item['raw-body'] ?? self::removePictures($body);
1472 } elseif (($type == 'Article') && empty($data['summary'])) {
1473 $data['summary'] = BBCode::toPlaintext(Plaintext::shorten(self::removePictures($body), 1000));
1476 if (empty($item['uid']) || !Feature::isEnabled($item['uid'], 'explicit_mentions')) {
1477 $body = self::prependMentions($body, $item['uri-id'], $item['author-link']);
1480 if ($type == 'Event') {
1481 $data = array_merge($data, self::createEvent($item));
1483 $regexp = "/[@!]\[url\=([^\[\]]*)\].*?\[\/url\]/ism";
1484 $body = preg_replace_callback($regexp, ['self', 'mentionCallback'], $body);
1486 $data['content'] = BBCode::convert($body, false, BBCode::ACTIVITYPUB);
1489 // The regular "content" field does contain a minimized HTML. This is done since systems like
1490 // Mastodon has got problems with - for example - embedded pictures.
1491 // The contentMap does contain the unmodified HTML.
1492 $language = self::getLanguage($item);
1493 if (!empty($language)) {
1494 $regexp = "/[@!]\[url\=([^\[\]]*)\].*?\[\/url\]/ism";
1495 $richbody = preg_replace_callback($regexp, ['self', 'mentionCallback'], $item['body']);
1496 $richbody = BBCode::removeAttachment($richbody);
1498 $data['contentMap'][$language] = BBCode::convert($richbody, false);
1501 $data['source'] = ['content' => $item['body'], 'mediaType' => "text/bbcode"];
1503 if (!empty($item['signed_text']) && ($item['uri'] != $item['thr-parent'])) {
1504 $data['diaspora:comment'] = $item['signed_text'];
1507 $data['attachment'] = self::createAttachmentList($item, $type);
1508 $data['tag'] = self::createTagList($item);
1510 if (empty($data['location']) && (!empty($item['coord']) || !empty($item['location']))) {
1511 $data['location'] = self::createLocation($item);
1514 if (!empty($item['app'])) {
1515 $data['generator'] = ['type' => 'Application', 'name' => $item['app']];
1518 $data = array_merge($data, $permission_block);
1524 * Fetches the language from the post, the user or the system.
1526 * @param array $item
1528 * @return string language string
1530 private static function getLanguage(array $item)
1532 // Try to fetch the language from the post itself
1533 if (!empty($item['language'])) {
1534 $languages = array_keys(json_decode($item['language'], true));
1535 if (!empty($languages[0])) {
1536 return $languages[0];
1540 // Otherwise use the user's language
1541 if (!empty($item['uid'])) {
1542 $user = DBA::selectFirst('user', ['language'], ['uid' => $item['uid']]);
1543 if (!empty($user['language'])) {
1544 return $user['language'];
1548 // And finally just use the system language
1549 return DI::config()->get('system', 'language');
1553 * Creates an an "add tag" entry
1555 * @param array $item
1556 * @param array $data activity data
1558 * @return array with activity data for adding tags
1559 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1560 * @throws \ImagickException
1562 private static function createAddTag($item, $data)
1564 $object = XML::parseString($item['object']);
1565 $target = XML::parseString($item["target"]);
1567 $data['diaspora:guid'] = $item['guid'];
1568 $data['actor'] = $item['author-link'];
1569 $data['target'] = (string)$target->id;
1570 $data['summary'] = BBCode::toPlaintext($item['body']);
1571 $data['object'] = ['id' => (string)$object->id, 'type' => 'tag', 'name' => (string)$object->title, 'content' => (string)$object->content];
1577 * Creates an announce object entry
1579 * @param array $item
1580 * @param array $data activity data
1582 * @return array with activity data
1583 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1584 * @throws \ImagickException
1586 private static function createAnnounce($item, $data)
1588 $orig_body = $item['body'];
1589 $announce = self::getAnnounceArray($item);
1590 if (empty($announce)) {
1591 $data['type'] = 'Create';
1592 $data['object'] = self::createNote($item);
1596 if (empty($announce['comment'])) {
1597 // Pure announce, without a quote
1598 $data['type'] = 'Announce';
1599 $data['object'] = $announce['object']['uri'];
1604 $data['type'] = 'Create';
1605 $item['body'] = $announce['comment'] . "\n" . $announce['object']['plink'];
1606 $data['object'] = self::createNote($item);
1608 /// @todo Finally descide how to implement this in AP. This is a possible way:
1609 $data['object']['attachment'][] = self::createNote($announce['object']);
1611 $data['object']['source']['content'] = $orig_body;
1616 * Return announce related data if the item is an annunce
1618 * @param array $item
1622 public static function getAnnounceArray($item)
1624 $reshared = Item::getShareArray($item);
1625 if (empty($reshared['guid'])) {
1629 $reshared_item = Item::selectFirst([], ['guid' => $reshared['guid']]);
1630 if (!DBA::isResult($reshared_item)) {
1634 if (!in_array($reshared_item['network'], [Protocol::ACTIVITYPUB, Protocol::DFRN])) {
1638 $profile = APContact::getByURL($reshared_item['author-link'], false);
1639 if (empty($profile)) {
1643 return ['object' => $reshared_item, 'actor' => $profile, 'comment' => $reshared['comment']];
1647 * Checks if the provided item array is an announce
1649 * @param array $item
1653 public static function isAnnounce($item)
1655 if (!empty($item['verb']) && ($item['verb'] == Activity::ANNOUNCE)) {
1659 $announce = self::getAnnounceArray($item);
1660 if (empty($announce)) {
1664 return empty($announce['comment']);
1668 * Creates an activity id for a given contact id
1670 * @param integer $cid Contact ID of target
1672 * @return bool|string activity id
1674 public static function activityIDFromContact($cid)
1676 $contact = DBA::selectFirst('contact', ['uid', 'id', 'created'], ['id' => $cid]);
1677 if (!DBA::isResult($contact)) {
1681 $hash = hash('ripemd128', $contact['uid'].'-'.$contact['id'].'-'.$contact['created']);
1682 $uuid = substr($hash, 0, 8). '-' . substr($hash, 8, 4) . '-' . substr($hash, 12, 4) . '-' . substr($hash, 16, 4) . '-' . substr($hash, 20, 12);
1683 return DI::baseUrl() . '/activity/' . $uuid;
1687 * Transmits a contact suggestion to a given inbox
1689 * @param integer $uid User ID
1690 * @param string $inbox Target inbox
1691 * @param integer $suggestion_id Suggestion ID
1693 * @return boolean was the transmission successful?
1694 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1696 public static function sendContactSuggestion($uid, $inbox, $suggestion_id)
1698 $owner = User::getOwnerDataById($uid);
1700 $suggestion = DI::fsuggest()->getById($suggestion_id);
1702 $data = ['@context' => ActivityPub::CONTEXT,
1703 'id' => DI::baseUrl() . '/activity/' . System::createGUID(),
1704 'type' => 'Announce',
1705 'actor' => $owner['url'],
1706 'object' => $suggestion->url,
1707 'content' => $suggestion->note,
1708 'instrument' => self::getService(),
1709 'to' => [ActivityPub::PUBLIC_COLLECTION],
1712 $signed = LDSignature::sign($data, $owner);
1714 Logger::log('Deliver profile deletion for user ' . $uid . ' to ' . $inbox . ' via ActivityPub', Logger::DEBUG);
1715 return HTTPSignature::transmit($signed, $inbox, $uid);
1719 * Transmits a profile relocation to a given inbox
1721 * @param integer $uid User ID
1722 * @param string $inbox Target inbox
1724 * @return boolean was the transmission successful?
1725 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1727 public static function sendProfileRelocation($uid, $inbox)
1729 $owner = User::getOwnerDataById($uid);
1731 $data = ['@context' => ActivityPub::CONTEXT,
1732 'id' => DI::baseUrl() . '/activity/' . System::createGUID(),
1733 'type' => 'dfrn:relocate',
1734 'actor' => $owner['url'],
1735 'object' => $owner['url'],
1736 'published' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
1737 'instrument' => self::getService(),
1738 'to' => [ActivityPub::PUBLIC_COLLECTION],
1741 $signed = LDSignature::sign($data, $owner);
1743 Logger::log('Deliver profile relocation for user ' . $uid . ' to ' . $inbox . ' via ActivityPub', Logger::DEBUG);
1744 return HTTPSignature::transmit($signed, $inbox, $uid);
1748 * Transmits a profile deletion to a given inbox
1750 * @param integer $uid User ID
1751 * @param string $inbox Target inbox
1753 * @return boolean was the transmission successful?
1754 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1756 public static function sendProfileDeletion($uid, $inbox)
1758 $owner = User::getOwnerDataById($uid);
1760 if (empty($owner)) {
1761 Logger::error('No owner data found, the deletion message cannot be processed.', ['user' => $uid]);
1765 if (empty($owner['uprvkey'])) {
1766 Logger::error('No private key for owner found, the deletion message cannot be processed.', ['user' => $uid]);
1770 $data = ['@context' => ActivityPub::CONTEXT,
1771 'id' => DI::baseUrl() . '/activity/' . System::createGUID(),
1773 'actor' => $owner['url'],
1774 'object' => $owner['url'],
1775 'published' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
1776 'instrument' => self::getService(),
1777 'to' => [ActivityPub::PUBLIC_COLLECTION],
1780 $signed = LDSignature::sign($data, $owner);
1782 Logger::log('Deliver profile deletion for user ' . $uid . ' to ' . $inbox . ' via ActivityPub', Logger::DEBUG);
1783 return HTTPSignature::transmit($signed, $inbox, $uid);
1787 * Transmits a profile change to a given inbox
1789 * @param integer $uid User ID
1790 * @param string $inbox Target inbox
1792 * @return boolean was the transmission successful?
1793 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1794 * @throws \ImagickException
1796 public static function sendProfileUpdate($uid, $inbox)
1798 $owner = User::getOwnerDataById($uid);
1799 $profile = APContact::getByURL($owner['url']);
1801 $data = ['@context' => ActivityPub::CONTEXT,
1802 'id' => DI::baseUrl() . '/activity/' . System::createGUID(),
1804 'actor' => $owner['url'],
1805 'object' => self::getProfile($uid),
1806 'published' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
1807 'instrument' => self::getService(),
1808 'to' => [$profile['followers']],
1811 $signed = LDSignature::sign($data, $owner);
1813 Logger::log('Deliver profile update for user ' . $uid . ' to ' . $inbox . ' via ActivityPub', Logger::DEBUG);
1814 return HTTPSignature::transmit($signed, $inbox, $uid);
1818 * Transmits a given activity to a target
1820 * @param string $activity Type name
1821 * @param string $target Target profile
1822 * @param integer $uid User ID
1824 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1825 * @throws \ImagickException
1826 * @throws \Exception
1828 public static function sendActivity($activity, $target, $uid, $id = '')
1830 $profile = APContact::getByURL($target);
1831 if (empty($profile['inbox'])) {
1832 Logger::warning('No inbox found for target', ['target' => $target, 'profile' => $profile]);
1836 $owner = User::getOwnerDataById($uid);
1839 $id = DI::baseUrl() . '/activity/' . System::createGUID();
1842 $data = ['@context' => ActivityPub::CONTEXT,
1844 'type' => $activity,
1845 'actor' => $owner['url'],
1846 'object' => $profile['url'],
1847 'instrument' => self::getService(),
1848 'to' => [$profile['url']]];
1850 Logger::log('Sending activity ' . $activity . ' to ' . $target . ' for user ' . $uid, Logger::DEBUG);
1852 $signed = LDSignature::sign($data, $owner);
1853 return HTTPSignature::transmit($signed, $profile['inbox'], $uid);
1857 * Transmits a "follow object" activity to a target
1858 * This is a preparation for sending automated "follow" requests when receiving "Announce" messages
1860 * @param string $object Object URL
1861 * @param string $target Target profile
1862 * @param integer $uid User ID
1864 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1865 * @throws \ImagickException
1866 * @throws \Exception
1868 public static function sendFollowObject($object, $target, $uid = 0)
1870 $profile = APContact::getByURL($target);
1871 if (empty($profile['inbox'])) {
1872 Logger::warning('No inbox found for target', ['target' => $target, 'profile' => $profile]);
1877 // Fetch the list of administrators
1878 $admin_mail = explode(',', str_replace(' ', '', DI::config()->get('config', 'admin_email')));
1880 // We need to use some user as a sender. It doesn't care who it will send. We will use an administrator account.
1881 $condition = ['verified' => true, 'blocked' => false, 'account_removed' => false, 'account_expired' => false, 'email' => $admin_mail];
1882 $first_user = DBA::selectFirst('user', ['uid'], $condition);
1883 $uid = $first_user['uid'];
1886 $condition = ['verb' => Activity::FOLLOW, 'uid' => 0, 'parent-uri' => $object,
1887 'author-id' => Contact::getPublicIdByUserId($uid)];
1888 if (Item::exists($condition)) {
1889 Logger::log('Follow for ' . $object . ' for user ' . $uid . ' does already exist.', Logger::DEBUG);
1893 $owner = User::getOwnerDataById($uid);
1895 $data = ['@context' => ActivityPub::CONTEXT,
1896 'id' => DI::baseUrl() . '/activity/' . System::createGUID(),
1898 'actor' => $owner['url'],
1899 'object' => $object,
1900 'instrument' => self::getService(),
1901 'to' => [$profile['url']]];
1903 Logger::log('Sending follow ' . $object . ' to ' . $target . ' for user ' . $uid, Logger::DEBUG);
1905 $signed = LDSignature::sign($data, $owner);
1906 return HTTPSignature::transmit($signed, $profile['inbox'], $uid);
1910 * Transmit a message that the contact request had been accepted
1912 * @param string $target Target profile
1914 * @param integer $uid User ID
1915 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1916 * @throws \ImagickException
1918 public static function sendContactAccept($target, $id, $uid)
1920 $profile = APContact::getByURL($target);
1921 if (empty($profile['inbox'])) {
1922 Logger::warning('No inbox found for target', ['target' => $target, 'profile' => $profile]);
1926 $owner = User::getOwnerDataById($uid);
1927 $data = ['@context' => ActivityPub::CONTEXT,
1928 'id' => DI::baseUrl() . '/activity/' . System::createGUID(),
1930 'actor' => $owner['url'],
1932 'id' => (string)$id,
1934 'actor' => $profile['url'],
1935 'object' => $owner['url']
1937 'instrument' => self::getService(),
1938 'to' => [$profile['url']]];
1940 Logger::debug('Sending accept to ' . $target . ' for user ' . $uid . ' with id ' . $id);
1942 $signed = LDSignature::sign($data, $owner);
1943 HTTPSignature::transmit($signed, $profile['inbox'], $uid);
1947 * Reject a contact request or terminates the contact relation
1949 * @param string $target Target profile
1951 * @param integer $uid User ID
1952 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1953 * @throws \ImagickException
1955 public static function sendContactReject($target, $id, $uid)
1957 $profile = APContact::getByURL($target);
1958 if (empty($profile['inbox'])) {
1959 Logger::warning('No inbox found for target', ['target' => $target, 'profile' => $profile]);
1963 $owner = User::getOwnerDataById($uid);
1964 $data = ['@context' => ActivityPub::CONTEXT,
1965 'id' => DI::baseUrl() . '/activity/' . System::createGUID(),
1967 'actor' => $owner['url'],
1969 'id' => (string)$id,
1971 'actor' => $profile['url'],
1972 'object' => $owner['url']
1974 'instrument' => self::getService(),
1975 'to' => [$profile['url']]];
1977 Logger::debug('Sending reject to ' . $target . ' for user ' . $uid . ' with id ' . $id);
1979 $signed = LDSignature::sign($data, $owner);
1980 HTTPSignature::transmit($signed, $profile['inbox'], $uid);
1984 * Transmits a message that we don't want to follow this contact anymore
1986 * @param string $target Target profile
1987 * @param integer $uid User ID
1988 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1989 * @throws \ImagickException
1990 * @throws \Exception
1991 * @return bool success
1993 public static function sendContactUndo($target, $cid, $uid)
1995 $profile = APContact::getByURL($target);
1996 if (empty($profile['inbox'])) {
1997 Logger::warning('No inbox found for target', ['target' => $target, 'profile' => $profile]);
2001 $object_id = self::activityIDFromContact($cid);
2002 if (empty($object_id)) {
2006 $id = DI::baseUrl() . '/activity/' . System::createGUID();
2008 $owner = User::getOwnerDataById($uid);
2009 $data = ['@context' => ActivityPub::CONTEXT,
2012 'actor' => $owner['url'],
2013 'object' => ['id' => $object_id, 'type' => 'Follow',
2014 'actor' => $owner['url'],
2015 'object' => $profile['url']],
2016 'instrument' => self::getService(),
2017 'to' => [$profile['url']]];
2019 Logger::log('Sending undo to ' . $target . ' for user ' . $uid . ' with id ' . $id, Logger::DEBUG);
2021 $signed = LDSignature::sign($data, $owner);
2022 return HTTPSignature::transmit($signed, $profile['inbox'], $uid);
2025 private static function prependMentions($body, int $uriid, string $authorLink)
2029 foreach (Tag::getByURIId($uriid, [Tag::IMPLICIT_MENTION]) as $tag) {
2030 $profile = Contact::getByURL($tag['url'], false, ['addr', 'contact-type', 'nick']);
2031 if (!empty($profile['addr'])
2032 && $profile['contact-type'] != Contact::TYPE_COMMUNITY
2033 && !strstr($body, $profile['addr'])
2034 && !strstr($body, $tag['url'])
2035 && $tag['url'] !== $authorLink
2037 $mentions[] = '@[url=' . $tag['url'] . ']' . $profile['nick'] . '[/url]';
2041 $mentions[] = $body;
2043 return implode(' ', $mentions);