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\Tag;
41 use Friendica\Model\User;
42 use Friendica\Protocol\Activity;
43 use Friendica\Protocol\ActivityPub;
44 use Friendica\Util\DateTimeFormat;
45 use Friendica\Util\HTTPSignature;
46 use Friendica\Util\Images;
47 use Friendica\Util\JsonLD;
48 use Friendica\Util\LDSignature;
49 use Friendica\Util\Map;
50 use Friendica\Util\Network;
51 use Friendica\Util\XML;
53 require_once 'include/api.php';
54 require_once 'mod/share.php';
57 * ActivityPub Transmitter Protocol class
65 * Add relay servers to the list of inboxes
67 * @param array $inboxes
68 * @return array inboxes with added relay servers
70 public static function addRelayServerInboxes(array $inboxes = [])
72 $contacts = DBA::select('apcontact', ['inbox'],
73 ["`type` = ? AND `url` IN (SELECT `url` FROM `contact` WHERE `uid` = ? AND `rel` IN (?, ?))",
74 'Application', 0, Contact::FOLLOWER, Contact::FRIEND]);
75 while ($contact = DBA::fetch($contacts)) {
76 $inboxes[] = $contact['inbox'];
78 DBA::close($contacts);
84 * Subscribe to a relay
86 * @param string $url Subscribe actor url
87 * @return bool success
89 public static function sendRelayFollow(string $url)
91 $contact = Contact::getByURL($url);
92 if (empty($contact)) {
96 $activity_id = ActivityPub\Transmitter::activityIDFromContact($contact['id']);
97 $success = ActivityPub\Transmitter::sendActivity('Follow', $url, 0, $activity_id);
99 $rel = $contact['rel'] == Contact::SHARING ? Contact::FRIEND : Contact::FOLLOWER;
100 DBA::update('contact', ['rel' => $rel], ['id' => $contact['id']]);
107 * Unsubscribe from a relay
109 * @param string $url Subscribe actor url
110 * @param bool $force Set the relay status as non follower even if unsubscribe hadn't worked
111 * @return bool success
113 public static function sendRelayUndoFollow(string $url, bool $force = false)
115 $contact = Contact::getByURL($url);
116 if (empty($contact)) {
120 $success = self::sendContactUndo($url, $contact['id'], 0);
121 if ($success || $force) {
122 $rel = $contact['rel'] == Contact::FRIEND ? Contact::SHARING : Contact::NOTHING;
123 DBA::update('contact', ['rel' => $rel], ['id' => $contact['id']]);
130 * Collects a list of contacts of the given owner
132 * @param array $owner Owner array
133 * @param int|array $rel The relevant value(s) contact.rel should match
134 * @param string $module The name of the relevant AP endpoint module (followers|following)
135 * @param integer $page Page number
137 * @return array of owners
140 public static function getContacts($owner, $rel, $module, $page = null)
144 'uid' => $owner['uid'],
151 $condition = DBA::buildCondition($parameters);
153 $sql = "SELECT COUNT(*) as `count`
155 JOIN `apcontact` ON `apcontact`.`url` = `contact`.`url`
158 $contacts = DBA::fetchFirst($sql, ...$parameters);
160 $modulePath = '/' . $module . '/';
162 $data = ['@context' => ActivityPub::CONTEXT];
163 $data['id'] = DI::baseUrl() . $modulePath . $owner['nickname'];
164 $data['type'] = 'OrderedCollection';
165 $data['totalItems'] = $contacts['count'];
167 // When we hide our friends we will only show the pure number but don't allow more.
168 $profile = Profile::getByUID($owner['uid']);
169 if (!empty($profile['hide-friends'])) {
174 $data['first'] = DI::baseUrl() . $modulePath . $owner['nickname'] . '?page=1';
176 $data['type'] = 'OrderedCollectionPage';
179 $sql = "SELECT `contact`.`url`
181 JOIN `apcontact` ON `apcontact`.`url` = `contact`.`url`
185 $parameters[] = ($page - 1) * 100;
188 $contacts = DBA::p($sql, ...$parameters);
189 while ($contact = DBA::fetch($contacts)) {
190 $list[] = $contact['url'];
192 DBA::close($contacts);
195 $data['next'] = DI::baseUrl() . $modulePath . $owner['nickname'] . '?page=' . ($page + 1);
198 $data['partOf'] = DI::baseUrl() . $modulePath . $owner['nickname'];
200 $data['orderedItems'] = $list;
207 * Public posts for the given owner
209 * @param array $owner Owner array
210 * @param integer $page Page number
211 * @param string $requester URL of requesting account
213 * @return array of posts
214 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
215 * @throws \ImagickException
217 public static function getOutbox($owner, $page = null, $requester = '')
219 $public_contact = Contact::getIdForURL($owner['url']);
220 $condition = ['uid' => 0, 'contact-id' => $public_contact,
221 'private' => [Item::PUBLIC, Item::UNLISTED]];
223 if (!empty($requester)) {
224 $requester_id = Contact::getIdForURL($requester, $owner['uid']);
225 if (!empty($requester_id)) {
226 $permissionSets = DI::permissionSet()->selectByContactId($requester_id, $owner['uid']);
227 if (!empty($permissionSets)) {
228 $condition = ['uid' => $owner['uid'], 'origin' => true,
229 'psid' => array_merge($permissionSets->column('id'),
230 [DI::permissionSet()->getIdFromACL($owner['uid'], '', '', '', '')])];
235 $condition = array_merge($condition,
236 ['author-id' => $public_contact,
237 'gravity' => [GRAVITY_PARENT, GRAVITY_COMMENT],
238 'deleted' => false, 'visible' => true, 'moderated' => false]);
240 $count = DBA::count('item', $condition);
242 $data = ['@context' => ActivityPub::CONTEXT];
243 $data['id'] = DI::baseUrl() . '/outbox/' . $owner['nickname'];
244 $data['type'] = 'OrderedCollection';
245 $data['totalItems'] = $count;
248 $data['first'] = DI::baseUrl() . '/outbox/' . $owner['nickname'] . '?page=1';
250 $data['type'] = 'OrderedCollectionPage';
253 $condition['parent-network'] = Protocol::NATIVE_SUPPORT;
255 $items = Item::select(['id'], $condition, ['limit' => [($page - 1) * 20, 20], 'order' => ['created' => true]]);
256 while ($item = Item::fetch($items)) {
257 $activity = self::createActivityFromItem($item['id'], true);
258 $activity['type'] = $activity['type'] == 'Update' ? 'Create' : $activity['type'];
260 // Only list "Create" activity objects here, no reshares
261 if (!empty($activity['object']) && ($activity['type'] == 'Create')) {
262 $list[] = $activity['object'];
267 $data['next'] = DI::baseUrl() . '/outbox/' . $owner['nickname'] . '?page=' . ($page + 1);
270 $data['partOf'] = DI::baseUrl() . '/outbox/' . $owner['nickname'];
272 $data['orderedItems'] = $list;
279 * Return the service array containing information the used software and it's url
281 * @return array with service data
283 private static function getService()
285 return ['type' => 'Service',
286 'name' => FRIENDICA_PLATFORM . " '" . FRIENDICA_CODENAME . "' " . FRIENDICA_VERSION . '-' . DB_UPDATE_VERSION,
287 'url' => DI::baseUrl()->get()];
291 * Return the ActivityPub profile of the given user
293 * @param integer $uid User ID
294 * @return array with profile data
295 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
297 public static function getProfile($uid)
300 $condition = ['uid' => $uid, 'blocked' => false, 'account_expired' => false,
301 'account_removed' => false, 'verified' => true];
302 $fields = ['guid', 'nickname', 'pubkey', 'account-type', 'page-flags'];
303 $user = DBA::selectFirst('user', $fields, $condition);
304 if (!DBA::isResult($user)) {
308 $fields = ['locality', 'region', 'country-name'];
309 $profile = DBA::selectFirst('profile', $fields, ['uid' => $uid]);
310 if (!DBA::isResult($profile)) {
314 $fields = ['name', 'url', 'location', 'about', 'avatar', 'photo'];
315 $contact = DBA::selectFirst('contact', $fields, ['uid' => $uid, 'self' => true]);
316 if (!DBA::isResult($contact)) {
320 $contact = User::getSystemAccount();
321 $user = ['guid' => '', 'nickname' => $contact['nick'], 'pubkey' => $contact['pubkey'],
322 'account-type' => $contact['contact-type'], 'page-flags' => User::PAGE_FLAGS_NORMAL];
323 $profile = ['locality' => '', 'region' => '', 'country-name' => ''];
326 $data = ['@context' => ActivityPub::CONTEXT];
327 $data['id'] = $contact['url'];
329 if (!empty($user['guid'])) {
330 $data['diaspora:guid'] = $user['guid'];
333 $data['type'] = ActivityPub::ACCOUNT_TYPES[$user['account-type']];
336 $data['following'] = DI::baseUrl() . '/following/' . $user['nickname'];
337 $data['followers'] = DI::baseUrl() . '/followers/' . $user['nickname'];
338 $data['inbox'] = DI::baseUrl() . '/inbox/' . $user['nickname'];
339 $data['outbox'] = DI::baseUrl() . '/outbox/' . $user['nickname'];
341 $data['inbox'] = DI::baseUrl() . '/friendica/inbox';
344 $data['preferredUsername'] = $user['nickname'];
345 $data['name'] = $contact['name'];
347 if (!empty($profile['country-name'] . $profile['region'] . $profile['locality'])) {
348 $data['vcard:hasAddress'] = ['@type' => 'vcard:Home', 'vcard:country-name' => $profile['country-name'],
349 'vcard:region' => $profile['region'], 'vcard:locality' => $profile['locality']];
352 if (!empty($contact['about'])) {
353 $data['summary'] = BBCode::convert($contact['about'], false);
356 $data['url'] = $contact['url'];
357 $data['manuallyApprovesFollowers'] = in_array($user['page-flags'], [User::PAGE_FLAGS_NORMAL, User::PAGE_FLAGS_PRVGROUP]);
358 $data['publicKey'] = ['id' => $contact['url'] . '#main-key',
359 'owner' => $contact['url'],
360 'publicKeyPem' => $user['pubkey']];
361 $data['endpoints'] = ['sharedInbox' => DI::baseUrl() . '/inbox'];
362 $data['icon'] = ['type' => 'Image',
363 'url' => $contact['photo']];
365 $data['generator'] = self::getService();
367 // tags: https://kitty.town/@inmysocks/100656097926961126.json
372 * @param string $username
374 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
376 public static function getDeletedUser($username)
379 '@context' => ActivityPub::CONTEXT,
380 'id' => DI::baseUrl() . '/profile/' . $username,
381 'type' => 'Tombstone',
382 'published' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
383 'updated' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
384 'deleted' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
389 * Returns an array with permissions of a given item array
393 * @return array with permissions
394 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
395 * @throws \ImagickException
397 private static function fetchPermissionBlockFromConversation($item)
399 if (empty($item['thr-parent'])) {
403 $condition = ['item-uri' => $item['thr-parent'], 'protocol' => Conversation::PARCEL_ACTIVITYPUB];
404 $conversation = DBA::selectFirst('conversation', ['source'], $condition);
405 if (!DBA::isResult($conversation)) {
409 $activity = json_decode($conversation['source'], true);
411 $actor = JsonLD::fetchElement($activity, 'actor', 'id');
412 $profile = APContact::getByURL($actor);
414 $item_profile = APContact::getByURL($item['author-link']);
415 $exclude[] = $item['author-link'];
417 if ($item['gravity'] == GRAVITY_PARENT) {
418 $exclude[] = $item['owner-link'];
421 $permissions['to'][] = $actor;
423 foreach (['to', 'cc', 'bto', 'bcc'] as $element) {
424 if (empty($activity[$element])) {
427 if (is_string($activity[$element])) {
428 $activity[$element] = [$activity[$element]];
431 foreach ($activity[$element] as $receiver) {
432 if (empty($receiver)) {
436 if (!empty($profile['followers']) && $receiver == $profile['followers'] && !empty($item_profile['followers'])) {
437 $permissions[$element][] = $item_profile['followers'];
438 } elseif (!in_array($receiver, $exclude)) {
439 $permissions[$element][] = $receiver;
447 * Creates an array of permissions from an item thread
449 * @param array $item Item array
450 * @param boolean $blindcopy addressing via "bcc" or "cc"?
451 * @param integer $last_id Last item id for adding receivers
452 * @param boolean $forum_mode "true" means that we are sending content to a forum
454 * @return array with permission data
455 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
456 * @throws \ImagickException
458 private static function createPermissionBlockForItem($item, $blindcopy, $last_id = 0, $forum_mode = false)
461 $last_id = $item['id'];
467 // Check if we should always deliver our stuff via BCC
468 if (!empty($item['uid'])) {
469 $profile = User::getOwnerDataById($item['uid']);
470 if (!empty($profile)) {
471 $always_bcc = $profile['hide-friends'];
472 $isforum = $profile['account-type'] == User::ACCOUNT_TYPE_COMMUNITY;
476 if (DI::config()->get('system', 'ap_always_bcc')) {
480 if ((self::isAnnounce($item) && !$isforum) || DI::config()->get('debug', 'total_ap_delivery')) {
481 // Will be activated in a later step
482 $networks = Protocol::FEDERATED;
484 // For now only send to these contacts:
485 $networks = [Protocol::ACTIVITYPUB, Protocol::OSTATUS];
488 $data = ['to' => [], 'cc' => [], 'bcc' => []];
490 if ($item['gravity'] == GRAVITY_PARENT) {
491 $actor_profile = APContact::getByURL($item['owner-link']);
493 $actor_profile = APContact::getByURL($item['author-link']);
496 $terms = Tag::getByURIId($item['uri-id'], [Tag::MENTION, Tag::IMPLICIT_MENTION, Tag::EXCLUSIVE_MENTION]);
498 if ($item['private'] != Item::PRIVATE) {
499 // Directly mention the original author upon a quoted reshare.
500 // Else just ensure that the original author receives the reshare.
501 $announce = self::getAnnounceArray($item);
502 if (!empty($announce['comment'])) {
503 $data['to'][] = $announce['actor']['url'];
504 } elseif (!empty($announce)) {
505 $data['cc'][] = $announce['actor']['url'];
508 $data = array_merge($data, self::fetchPermissionBlockFromConversation($item));
510 // Check if the item is completely public or unlisted
511 if ($item['private'] == Item::PUBLIC) {
512 $data['to'][] = ActivityPub::PUBLIC_COLLECTION;
514 $data['cc'][] = ActivityPub::PUBLIC_COLLECTION;
517 foreach ($terms as $term) {
518 $profile = APContact::getByURL($term['url'], false);
519 if (!empty($profile)) {
520 $data['to'][] = $profile['url'];
524 $receiver_list = Item::enumeratePermissions($item, true);
526 foreach ($terms as $term) {
527 $cid = Contact::getIdForURL($term['url'], $item['uid']);
528 if (!empty($cid) && in_array($cid, $receiver_list)) {
529 $contact = DBA::selectFirst('contact', ['url', 'network', 'protocol'], ['id' => $cid]);
530 if (!DBA::isResult($contact) || (!in_array($contact['network'], $networks) && ($contact['protocol'] != Protocol::ACTIVITYPUB))) {
534 if ($isforum && DBA::isResult($contact) && ($contact['dfrn'] == Protocol::DFRN)) {
538 if (!empty($profile = APContact::getByURL($contact['url'], false))) {
539 $data['to'][] = $profile['url'];
544 foreach ($receiver_list as $receiver) {
545 $contact = DBA::selectFirst('contact', ['url', 'hidden', 'network', 'protocol'], ['id' => $receiver]);
546 if (!DBA::isResult($contact) || (!in_array($contact['network'], $networks) && ($contact['protocol'] != Protocol::ACTIVITYPUB))) {
550 if ($isforum && DBA::isResult($contact) && ($contact['dfrn'] == Protocol::DFRN)) {
554 if (!empty($profile = APContact::getByURL($contact['url'], false))) {
555 if ($contact['hidden'] || $always_bcc) {
556 $data['bcc'][] = $profile['url'];
558 $data['cc'][] = $profile['url'];
564 if (!empty($item['parent'])) {
565 $parents = Item::select(['id', 'author-link', 'owner-link', 'gravity', 'uri'], ['parent' => $item['parent']]);
566 while ($parent = Item::fetch($parents)) {
567 if ($parent['gravity'] == GRAVITY_PARENT) {
568 $profile = APContact::getByURL($parent['owner-link'], false);
569 if (!empty($profile)) {
570 if ($item['gravity'] != GRAVITY_PARENT) {
571 // Comments to forums are directed to the forum
572 // But comments to forums aren't directed to the followers collection
573 // This rule is only valid when the actor isn't the forum.
574 // The forum needs to transmit their content to their followers.
575 if (($profile['type'] == 'Group') && ($profile['url'] != $actor_profile['url'])) {
576 $data['to'][] = $profile['url'];
578 $data['cc'][] = $profile['url'];
579 if (($item['private'] != Item::PRIVATE) && !empty($actor_profile['followers'])) {
580 $data['cc'][] = $actor_profile['followers'];
584 // Public thread parent post always are directed to the followers
585 if (($item['private'] != Item::PRIVATE) && !$forum_mode) {
586 $data['cc'][] = $actor_profile['followers'];
592 // Don't include data from future posts
593 if ($parent['id'] >= $last_id) {
597 $profile = APContact::getByURL($parent['author-link'], false);
598 if (!empty($profile)) {
599 if (($profile['type'] == 'Group') || ($parent['uri'] == $item['thr-parent'])) {
600 $data['to'][] = $profile['url'];
602 $data['cc'][] = $profile['url'];
606 DBA::close($parents);
609 $data['to'] = array_unique($data['to']);
610 $data['cc'] = array_unique($data['cc']);
611 $data['bcc'] = array_unique($data['bcc']);
613 if (($key = array_search($item['author-link'], $data['to'])) !== false) {
614 unset($data['to'][$key]);
617 if (($key = array_search($item['author-link'], $data['cc'])) !== false) {
618 unset($data['cc'][$key]);
621 if (($key = array_search($item['author-link'], $data['bcc'])) !== false) {
622 unset($data['bcc'][$key]);
625 foreach ($data['to'] as $to) {
626 if (($key = array_search($to, $data['cc'])) !== false) {
627 unset($data['cc'][$key]);
630 if (($key = array_search($to, $data['bcc'])) !== false) {
631 unset($data['bcc'][$key]);
635 foreach ($data['cc'] as $cc) {
636 if (($key = array_search($cc, $data['bcc'])) !== false) {
637 unset($data['bcc'][$key]);
641 $receivers = ['to' => array_values($data['to']), 'cc' => array_values($data['cc']), 'bcc' => array_values($data['bcc'])];
644 unset($receivers['bcc']);
651 * Check if an inbox is archived
653 * @param string $url Inbox url
655 * @return boolean "true" if inbox is archived
657 private static function archivedInbox($url)
659 return DBA::exists('inbox-status', ['url' => $url, 'archive' => true]);
663 * Fetches a list of inboxes of followers of a given user
665 * @param integer $uid User ID
666 * @param boolean $personal fetch personal inboxes
668 * @return array of follower inboxes
669 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
670 * @throws \ImagickException
672 public static function fetchTargetInboxesforUser($uid, $personal = false)
678 if (!empty($item['uid'])) {
679 $profile = User::getOwnerDataById($item['uid']);
680 if (!empty($profile)) {
681 $isforum = $profile['account-type'] == User::ACCOUNT_TYPE_COMMUNITY;
685 if (DI::config()->get('debug', 'total_ap_delivery')) {
686 // Will be activated in a later step
687 $networks = Protocol::FEDERATED;
689 // For now only send to these contacts:
690 $networks = [Protocol::ACTIVITYPUB, Protocol::OSTATUS];
693 $condition = ['uid' => $uid, 'archive' => false, 'pending' => false];
696 $condition['rel'] = [Contact::FOLLOWER, Contact::FRIEND];
699 $contacts = DBA::select('contact', ['url', 'network', 'protocol'], $condition);
700 while ($contact = DBA::fetch($contacts)) {
701 if (Contact::isLocal($contact['url'])) {
705 if (!in_array($contact['network'], $networks) && ($contact['protocol'] != Protocol::ACTIVITYPUB)) {
709 if ($isforum && ($contact['dfrn'] == Protocol::DFRN)) {
713 if (Network::isUrlBlocked($contact['url'])) {
717 $profile = APContact::getByURL($contact['url'], false);
718 if (!empty($profile)) {
719 if (empty($profile['sharedinbox']) || $personal) {
720 $target = $profile['inbox'];
722 $target = $profile['sharedinbox'];
724 if (!self::archivedInbox($target)) {
725 $inboxes[$target] = $target;
729 DBA::close($contacts);
735 * Fetches an array of inboxes for the given item and user
737 * @param array $item Item array
738 * @param integer $uid User ID
739 * @param boolean $personal fetch personal inboxes
740 * @param integer $last_id Last item id for adding receivers
741 * @param boolean $forum_mode "true" means that we are sending content to a forum
742 * @return array with inboxes
743 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
744 * @throws \ImagickException
746 public static function fetchTargetInboxes($item, $uid, $personal = false, $last_id = 0, $forum_mode = false)
748 $permissions = self::createPermissionBlockForItem($item, true, $last_id, $forum_mode);
749 if (empty($permissions)) {
755 if ($item['gravity'] == GRAVITY_ACTIVITY) {
756 $item_profile = APContact::getByURL($item['author-link'], false);
758 $item_profile = APContact::getByURL($item['owner-link'], false);
761 if (empty($item_profile)) {
765 $profile_uid = User::getIdForURL($item_profile['url']);
767 foreach (['to', 'cc', 'bto', 'bcc'] as $element) {
768 if (empty($permissions[$element])) {
772 $blindcopy = in_array($element, ['bto', 'bcc']);
774 foreach ($permissions[$element] as $receiver) {
775 if (empty($receiver) || Network::isUrlBlocked($receiver)) {
779 if ($item_profile && ($receiver == $item_profile['followers']) && ($uid == $profile_uid)) {
780 $inboxes = array_merge($inboxes, self::fetchTargetInboxesforUser($uid, $personal));
782 if (Contact::isLocal($receiver)) {
786 $profile = APContact::getByURL($receiver, false);
787 if (!empty($profile)) {
788 if (empty($profile['sharedinbox']) || $personal || $blindcopy) {
789 $target = $profile['inbox'];
791 $target = $profile['sharedinbox'];
793 if (!self::archivedInbox($target)) {
794 $inboxes[$target] = $target;
805 * Creates an array in the structure of the item table for a given mail id
807 * @param integer $mail_id
812 public static function ItemArrayFromMail($mail_id)
814 $mail = DBA::selectFirst('mail', [], ['id' => $mail_id]);
815 if (!DBA::isResult($mail)) {
819 $mail['uri-id'] = ItemURI::insert(['uri' => $mail['uri'], 'guid' => $mail['guid']]);
821 $reply = DBA::selectFirst('mail', ['uri'], ['parent-uri' => $mail['parent-uri'], 'reply' => false]);
823 // Making the post more compatible for Mastodon by:
824 // - Making it a note and not an article (no title)
825 // - Moving the title into the "summary" field that is used as a "content warning"
826 $mail['body'] = '[abstract]' . $mail['title'] . "[/abstract]\n" . $mail['body'];
829 $mail['author-link'] = $mail['owner-link'] = $mail['from-url'];
830 $mail['allow_cid'] = '<'.$mail['contact-id'].'>';
831 $mail['allow_gid'] = '';
832 $mail['deny_cid'] = '';
833 $mail['deny_gid'] = '';
834 $mail['private'] = true;
835 $mail['deleted'] = false;
836 $mail['edited'] = $mail['created'];
837 $mail['plink'] = $mail['uri'];
838 $mail['thr-parent'] = $reply['uri'];
839 $mail['gravity'] = ($mail['reply'] ? GRAVITY_COMMENT: GRAVITY_PARENT);
841 $mail['event-type'] = '';
842 $mail['attach'] = '';
850 * Creates an activity array for a given mail id
852 * @param integer $mail_id
853 * @param boolean $object_mode Is the activity item is used inside another object?
855 * @return array of activity
858 public static function createActivityFromMail($mail_id, $object_mode = false)
860 $mail = self::ItemArrayFromMail($mail_id);
864 $object = self::createNote($mail);
867 $data = ['@context' => ActivityPub::CONTEXT];
872 $data['id'] = $mail['uri'] . '/Create';
873 $data['type'] = 'Create';
874 $data['actor'] = $mail['author-link'];
875 $data['published'] = DateTimeFormat::utc($mail['created'] . '+00:00', DateTimeFormat::ATOM);
876 $data['instrument'] = self::getService();
877 $data = array_merge($data, self::createPermissionBlockForItem($mail, true));
879 if (empty($data['to']) && !empty($data['cc'])) {
880 $data['to'] = $data['cc'];
883 if (empty($data['to']) && !empty($data['bcc'])) {
884 $data['to'] = $data['bcc'];
890 $object['to'] = $data['to'];
891 $object['tag'] = [['type' => 'Mention', 'href' => $object['to'][0], 'name' => '']];
893 unset($object['cc']);
894 unset($object['bcc']);
896 $data['directMessage'] = true;
898 $data['object'] = $object;
900 $owner = User::getOwnerDataById($mail['uid']);
902 if (!$object_mode && !empty($owner)) {
903 return LDSignature::sign($data, $owner);
910 * Returns the activity type of a given item
914 * @return string with activity type
915 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
916 * @throws \ImagickException
918 private static function getTypeOfItem($item)
922 // Only check for a reshare, if it is a real reshare and no quoted reshare
923 if (strpos($item['body'], "[share") === 0) {
924 $announce = self::getAnnounceArray($item);
925 $reshared = !empty($announce);
930 } elseif ($item['verb'] == Activity::POST) {
931 if ($item['created'] == $item['edited']) {
936 } elseif ($item['verb'] == Activity::LIKE) {
938 } elseif ($item['verb'] == Activity::DISLIKE) {
940 } elseif ($item['verb'] == Activity::ATTEND) {
942 } elseif ($item['verb'] == Activity::ATTENDNO) {
944 } elseif ($item['verb'] == Activity::ATTENDMAYBE) {
945 $type = 'TentativeAccept';
946 } elseif ($item['verb'] == Activity::FOLLOW) {
948 } elseif ($item['verb'] == Activity::TAG) {
950 } elseif ($item['verb'] == Activity::ANNOUNCE) {
960 * Creates the activity or fetches it from the cache
962 * @param integer $item_id
963 * @param boolean $force Force new cache entry
965 * @return array with the activity
968 public static function createCachedActivityFromItem($item_id, $force = false)
970 $cachekey = 'APDelivery:createActivity:' . $item_id;
973 $data = DI::cache()->get($cachekey);
974 if (!is_null($data)) {
979 $data = self::createActivityFromItem($item_id);
981 DI::cache()->set($cachekey, $data, Duration::QUARTER_HOUR);
986 * Creates an activity array for a given item id
988 * @param integer $item_id
989 * @param boolean $object_mode Is the activity item is used inside another object?
991 * @return array of activity
994 public static function createActivityFromItem($item_id, $object_mode = false)
996 Logger::info('Fetching activity', ['item' => $item_id]);
997 $item = Item::selectFirst([], ['id' => $item_id, 'parent-network' => Protocol::NATIVE_SUPPORT]);
998 if (!DBA::isResult($item)) {
1002 // In case of a forum post ensure to return the original post if author and forum are on the same machine
1003 if (!empty($item['forum_mode'])) {
1004 $author = Contact::getById($item['author-id'], ['nurl']);
1005 if (!empty($author['nurl'])) {
1006 $self = Contact::selectFirst(['uid'], ['nurl' => $author['nurl'], 'self' => true]);
1007 if (!empty($self['uid'])) {
1008 $item = Item::selectFirst([], ['uri-id' => $item['uri-id'], 'uid' => $self['uid']]);
1014 $condition = ['item-uri' => $item['uri'], 'protocol' => Conversation::PARCEL_ACTIVITYPUB];
1015 $conversation = DBA::selectFirst('conversation', ['source'], $condition);
1016 if (DBA::isResult($conversation)) {
1017 $data = json_decode($conversation['source'], true);
1018 if (!empty($data['type'])) {
1019 if (in_array($data['type'], ['Create', 'Update'])) {
1021 unset($data['@context']);
1022 unset($data['signature']);
1024 Logger::info('Return stored conversation', ['item' => $item_id]);
1026 } elseif (in_array('as:' . $data['type'], Receiver::CONTENT_TYPES)) {
1027 if (!empty($data['@context'])) {
1028 $context = $data['@context'];
1029 unset($data['@context']);
1031 unset($data['actor']);
1037 $type = self::getTypeOfItem($item);
1040 if (!$object_mode) {
1041 $data = ['@context' => $context ?? ActivityPub::CONTEXT];
1043 if ($item['deleted'] && ($item['gravity'] == GRAVITY_ACTIVITY)) {
1045 } elseif ($item['deleted']) {
1052 if (($item['gravity'] == GRAVITY_ACTIVITY) && ($type != 'Undo')) {
1053 $data['id'] = $item['uri'];
1055 $data['id'] = $item['uri'] . '/' . $type;
1058 $data['type'] = $type;
1060 if (($type != 'Announce') || ($item['gravity'] != GRAVITY_PARENT)) {
1061 $data['actor'] = $item['author-link'];
1063 $data['actor'] = $item['owner-link'];
1066 $data['published'] = DateTimeFormat::utc($item['created'] . '+00:00', DateTimeFormat::ATOM);
1068 $data['instrument'] = self::getService();
1070 $data = array_merge($data, self::createPermissionBlockForItem($item, false));
1072 if (in_array($data['type'], ['Create', 'Update', 'Delete'])) {
1073 $data['object'] = $object ?? self::createNote($item);
1074 } elseif ($data['type'] == 'Add') {
1075 $data = self::createAddTag($item, $data);
1076 } elseif ($data['type'] == 'Announce') {
1077 if ($item['verb'] == ACTIVITY::ANNOUNCE) {
1078 $data['object'] = $item['thr-parent'];
1080 $data = self::createAnnounce($item, $data);
1082 } elseif ($data['type'] == 'Follow') {
1083 $data['object'] = $item['parent-uri'];
1084 } elseif ($data['type'] == 'Undo') {
1085 $data['object'] = self::createActivityFromItem($item_id, true);
1087 $data['diaspora:guid'] = $item['guid'];
1088 if (!empty($item['signed_text'])) {
1089 $data['diaspora:like'] = $item['signed_text'];
1091 $data['object'] = $item['thr-parent'];
1094 if (!empty($item['contact-uid'])) {
1095 $uid = $item['contact-uid'];
1097 $uid = $item['uid'];
1100 $owner = User::getOwnerDataById($uid);
1102 Logger::info('Fetched activity', ['item' => $item_id, 'uid' => $uid]);
1104 // We don't sign if we aren't the actor. This is important for relaying content especially for forums
1105 if (!$object_mode && !empty($owner) && ($data['actor'] == $owner['url'])) {
1106 return LDSignature::sign($data, $owner);
1111 /// @todo Create "conversation" entry
1115 * Creates a location entry for a given item array
1117 * @param array $item
1119 * @return array with location array
1121 private static function createLocation($item)
1123 $location = ['type' => 'Place'];
1125 if (!empty($item['location'])) {
1126 $location['name'] = $item['location'];
1131 if (empty($item['coord'])) {
1132 $coord = Map::getCoordinates($item['location']);
1134 $coords = explode(' ', $item['coord']);
1135 if (count($coords) == 2) {
1136 $coord = ['lat' => $coords[0], 'lon' => $coords[1]];
1140 if (!empty($coord['lat']) && !empty($coord['lon'])) {
1141 $location['latitude'] = $coord['lat'];
1142 $location['longitude'] = $coord['lon'];
1149 * Returns a tag array for a given item array
1151 * @param array $item
1153 * @return array of tags
1154 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1156 private static function createTagList($item)
1160 $terms = Tag::getByURIId($item['uri-id'], [Tag::HASHTAG, Tag::MENTION, Tag::IMPLICIT_MENTION, Tag::EXCLUSIVE_MENTION]);
1161 foreach ($terms as $term) {
1162 if ($term['type'] == Tag::HASHTAG) {
1163 $url = DI::baseUrl() . '/search?tag=' . urlencode($term['name']);
1164 $tags[] = ['type' => 'Hashtag', 'href' => $url, 'name' => '#' . $term['name']];
1166 $contact = Contact::getByURL($term['url'], false, ['addr']);
1167 if (empty($contact)) {
1170 if (!empty($contact['addr'])) {
1171 $mention = '@' . $contact['addr'];
1173 $mention = '@' . $term['url'];
1176 $tags[] = ['type' => 'Mention', 'href' => $term['url'], 'name' => $mention];
1180 $announce = self::getAnnounceArray($item);
1181 // Mention the original author upon commented reshares
1182 if (!empty($announce['comment'])) {
1183 $tags[] = ['type' => 'Mention', 'href' => $announce['actor']['url'], 'name' => '@' . $announce['actor']['addr']];
1190 * Adds attachment data to the JSON document
1192 * @param array $item Data of the item that is to be posted
1193 * @param string $type Object type
1195 * @return array with attachment data
1196 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1198 private static function createAttachmentList($item, $type)
1202 // Currently deactivated, since it creates side effects on Mastodon and Pleroma.
1203 // It will be reactivated, once this cleared.
1205 $attach_data = BBCode::getAttachmentData($item['body']);
1206 if (!empty($attach_data['url'])) {
1207 $attachment = ['type' => 'Page',
1208 'mediaType' => 'text/html',
1209 'url' => $attach_data['url']];
1211 if (!empty($attach_data['title'])) {
1212 $attachment['name'] = $attach_data['title'];
1215 if (!empty($attach_data['description'])) {
1216 $attachment['summary'] = $attach_data['description'];
1219 if (!empty($attach_data['image'])) {
1220 $imgdata = Images::getInfoFromURLCached($attach_data['image']);
1222 $attachment['icon'] = ['type' => 'Image',
1223 'mediaType' => $imgdata['mime'],
1224 'width' => $imgdata[0],
1225 'height' => $imgdata[1],
1226 'url' => $attach_data['image']];
1230 $attachments[] = $attachment;
1233 $arr = explode('[/attach],', $item['attach']);
1235 foreach ($arr as $r) {
1237 $cnt = preg_match('|\[attach\]href=\"(.*?)\" length=\"(.*?)\" type=\"(.*?)\" title=\"(.*?)\"|', $r, $matches);
1239 $attributes = ['type' => 'Document',
1240 'mediaType' => $matches[3],
1241 'url' => $matches[1],
1244 if (trim($matches[4]) != '') {
1245 $attributes['name'] = trim($matches[4]);
1248 $attachments[] = $attributes;
1253 if ($type != 'Note') {
1254 return $attachments;
1257 // Simplify image codes
1258 $body = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '[img]$3[/img]', $item['body']);
1260 // Grab all pictures without alternative descriptions and create attachments out of them
1261 if (preg_match_all("/\[img\]([^\[\]]*)\[\/img\]/Usi", $body, $pictures)) {
1262 foreach ($pictures[1] as $picture) {
1263 $imgdata = Images::getInfoFromURLCached($picture);
1265 $attachments[] = ['type' => 'Document',
1266 'mediaType' => $imgdata['mime'],
1273 // Grab all pictures with alternative description and create attachments out of them
1274 if (preg_match_all("/\[img=([^\[\]]*)\]([^\[\]]*)\[\/img\]/Usi", $body, $pictures, PREG_SET_ORDER)) {
1275 foreach ($pictures as $picture) {
1276 $imgdata = Images::getInfoFromURLCached($picture[1]);
1278 $attachments[] = ['type' => 'Document',
1279 'mediaType' => $imgdata['mime'],
1280 'url' => $picture[1],
1281 'name' => $picture[2]];
1286 return $attachments;
1290 * Callback function to replace a Friendica style mention in a mention that is used on AP
1292 * @param array $match Matching values for the callback
1293 * @return string Replaced mention
1294 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1296 private static function mentionCallback($match)
1298 if (empty($match[1])) {
1302 $data = Contact::getByURL($match[1], false, ['url', 'nick']);
1303 if (empty($data['nick'])) {
1307 return '@[url=' . $data['url'] . ']' . $data['nick'] . '[/url]';
1311 * Remove image elements since they are added as attachment
1313 * @param string $body
1315 * @return string with removed images
1317 private static function removePictures($body)
1319 // Simplify image codes
1320 $body = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '[img]$3[/img]', $body);
1321 $body = preg_replace("/\[img\=(.*?)\](.*?)\[\/img\]/ism", '[img]$1[/img]', $body);
1323 // Now remove local links
1324 $body = preg_replace_callback(
1325 '/\[url=([^\[\]]*)\]\[img\](.*)\[\/img\]\[\/url\]/Usi',
1327 // We remove the link when it is a link to a local photo page
1328 if (Photo::isLocalPage($match[1])) {
1331 // otherwise we just return the link
1332 return '[url]' . $match[1] . '[/url]';
1337 // Remove all pictures
1338 $body = preg_replace("/\[img\]([^\[\]]*)\[\/img\]/Usi", '', $body);
1344 * Fetches the "context" value for a givem item array from the "conversation" table
1346 * @param array $item
1348 * @return string with context url
1349 * @throws \Exception
1351 private static function fetchContextURLForItem($item)
1353 $conversation = DBA::selectFirst('conversation', ['conversation-href', 'conversation-uri'], ['item-uri' => $item['parent-uri']]);
1354 if (DBA::isResult($conversation) && !empty($conversation['conversation-href'])) {
1355 $context_uri = $conversation['conversation-href'];
1356 } elseif (DBA::isResult($conversation) && !empty($conversation['conversation-uri'])) {
1357 $context_uri = $conversation['conversation-uri'];
1359 $context_uri = $item['parent-uri'] . '#context';
1361 return $context_uri;
1365 * Returns if the post contains sensitive content ("nsfw")
1367 * @param integer $uri_id
1370 * @throws \Exception
1372 private static function isSensitive($uri_id)
1374 return DBA::exists('tag-view', ['uri-id' => $uri_id, 'name' => 'nsfw']);
1378 * Creates event data
1380 * @param array $item
1382 * @return array with the event data
1383 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1385 public static function createEvent($item)
1388 $event['name'] = $item['event-summary'];
1389 $event['content'] = BBCode::convert($item['event-desc'], false, BBCode::ACTIVITYPUB);
1390 $event['startTime'] = DateTimeFormat::utc($item['event-start'] . '+00:00', DateTimeFormat::ATOM);
1392 if (!$item['event-nofinish']) {
1393 $event['endTime'] = DateTimeFormat::utc($item['event-finish'] . '+00:00', DateTimeFormat::ATOM);
1396 if (!empty($item['event-location'])) {
1397 $item['location'] = $item['event-location'];
1398 $event['location'] = self::createLocation($item);
1405 * Creates a note/article object array
1407 * @param array $item
1409 * @return array with the object data
1410 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1411 * @throws \ImagickException
1413 public static function createNote($item)
1419 if ($item['event-type'] == 'event') {
1421 } elseif (!empty($item['title'])) {
1427 if ($item['deleted']) {
1428 $type = 'Tombstone';
1432 $data['id'] = $item['uri'];
1433 $data['type'] = $type;
1435 if ($item['deleted']) {
1439 $data['summary'] = BBCode::toPlaintext(BBCode::getAbstract($item['body'], Protocol::ACTIVITYPUB));
1441 if ($item['uri'] != $item['thr-parent']) {
1442 $data['inReplyTo'] = $item['thr-parent'];
1444 $data['inReplyTo'] = null;
1447 $data['diaspora:guid'] = $item['guid'];
1448 $data['published'] = DateTimeFormat::utc($item['created'] . '+00:00', DateTimeFormat::ATOM);
1450 if ($item['created'] != $item['edited']) {
1451 $data['updated'] = DateTimeFormat::utc($item['edited'] . '+00:00', DateTimeFormat::ATOM);
1454 $data['url'] = $item['plink'];
1455 $data['attributedTo'] = $item['author-link'];
1456 $data['sensitive'] = self::isSensitive($item['uri-id']);
1457 $data['context'] = self::fetchContextURLForItem($item);
1459 if (!empty($item['title'])) {
1460 $data['name'] = BBCode::toPlaintext($item['title'], false);
1463 $permission_block = self::createPermissionBlockForItem($item, false);
1465 $body = $item['body'];
1467 if (empty($item['uid']) || !Feature::isEnabled($item['uid'], 'explicit_mentions')) {
1468 $body = self::prependMentions($body, $item['uri-id']);
1471 if ($type == 'Note') {
1472 $body = self::removePictures($body);
1473 } elseif (($type == 'Article') && empty($data['summary'])) {
1474 $data['summary'] = BBCode::toPlaintext(Plaintext::shorten(self::removePictures($body), 1000));
1477 if ($type == 'Event') {
1478 $data = array_merge($data, self::createEvent($item));
1480 $regexp = "/[@!]\[url\=([^\[\]]*)\].*?\[\/url\]/ism";
1481 $body = preg_replace_callback($regexp, ['self', 'mentionCallback'], $body);
1483 $data['content'] = BBCode::convert($body, false, BBCode::ACTIVITYPUB);
1486 // The regular "content" field does contain a minimized HTML. This is done since systems like
1487 // Mastodon has got problems with - for example - embedded pictures.
1488 // The contentMap does contain the unmodified HTML.
1489 $language = self::getLanguage($item);
1490 if (!empty($language)) {
1491 $regexp = "/[@!]\[url\=([^\[\]]*)\].*?\[\/url\]/ism";
1492 $richbody = preg_replace_callback($regexp, ['self', 'mentionCallback'], $item['body']);
1493 $richbody = BBCode::removeAttachment($richbody);
1495 $data['contentMap'][$language] = BBCode::convert($richbody, false);
1498 $data['source'] = ['content' => $item['body'], 'mediaType' => "text/bbcode"];
1500 if (!empty($item['signed_text']) && ($item['uri'] != $item['thr-parent'])) {
1501 $data['diaspora:comment'] = $item['signed_text'];
1504 $data['attachment'] = self::createAttachmentList($item, $type);
1505 $data['tag'] = self::createTagList($item);
1507 if (empty($data['location']) && (!empty($item['coord']) || !empty($item['location']))) {
1508 $data['location'] = self::createLocation($item);
1511 if (!empty($item['app'])) {
1512 $data['generator'] = ['type' => 'Application', 'name' => $item['app']];
1515 $data = array_merge($data, $permission_block);
1521 * Fetches the language from the post, the user or the system.
1523 * @param array $item
1525 * @return string language string
1527 private static function getLanguage(array $item)
1529 // Try to fetch the language from the post itself
1530 if (!empty($item['language'])) {
1531 $languages = array_keys(json_decode($item['language'], true));
1532 if (!empty($languages[0])) {
1533 return $languages[0];
1537 // Otherwise use the user's language
1538 if (!empty($item['uid'])) {
1539 $user = DBA::selectFirst('user', ['language'], ['uid' => $item['uid']]);
1540 if (!empty($user['language'])) {
1541 return $user['language'];
1545 // And finally just use the system language
1546 return DI::config()->get('system', 'language');
1550 * Creates an an "add tag" entry
1552 * @param array $item
1553 * @param array $data activity data
1555 * @return array with activity data for adding tags
1556 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1557 * @throws \ImagickException
1559 private static function createAddTag($item, $data)
1561 $object = XML::parseString($item['object']);
1562 $target = XML::parseString($item["target"]);
1564 $data['diaspora:guid'] = $item['guid'];
1565 $data['actor'] = $item['author-link'];
1566 $data['target'] = (string)$target->id;
1567 $data['summary'] = BBCode::toPlaintext($item['body']);
1568 $data['object'] = ['id' => (string)$object->id, 'type' => 'tag', 'name' => (string)$object->title, 'content' => (string)$object->content];
1574 * Creates an announce object entry
1576 * @param array $item
1577 * @param array $data activity data
1579 * @return array with activity data
1580 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1581 * @throws \ImagickException
1583 private static function createAnnounce($item, $data)
1585 $orig_body = $item['body'];
1586 $announce = self::getAnnounceArray($item);
1587 if (empty($announce)) {
1588 $data['type'] = 'Create';
1589 $data['object'] = self::createNote($item);
1593 if (empty($announce['comment'])) {
1594 // Pure announce, without a quote
1595 $data['type'] = 'Announce';
1596 $data['object'] = $announce['object']['uri'];
1601 $data['type'] = 'Create';
1602 $item['body'] = $announce['comment'] . "\n" . $announce['object']['plink'];
1603 $data['object'] = self::createNote($item);
1605 /// @todo Finally descide how to implement this in AP. This is a possible way:
1606 $data['object']['attachment'][] = self::createNote($announce['object']);
1608 $data['object']['source']['content'] = $orig_body;
1613 * Return announce related data if the item is an annunce
1615 * @param array $item
1619 public static function getAnnounceArray($item)
1621 $reshared = Item::getShareArray($item);
1622 if (empty($reshared['guid'])) {
1626 $reshared_item = Item::selectFirst([], ['guid' => $reshared['guid']]);
1627 if (!DBA::isResult($reshared_item)) {
1631 if (!in_array($reshared_item['network'], [Protocol::ACTIVITYPUB, Protocol::DFRN])) {
1635 $profile = APContact::getByURL($reshared_item['author-link'], false);
1636 if (empty($profile)) {
1640 return ['object' => $reshared_item, 'actor' => $profile, 'comment' => $reshared['comment']];
1644 * Checks if the provided item array is an announce
1646 * @param array $item
1650 public static function isAnnounce($item)
1652 if (!empty($item['verb']) && ($item['verb'] == Activity::ANNOUNCE)) {
1656 $announce = self::getAnnounceArray($item);
1657 if (empty($announce)) {
1661 return empty($announce['comment']);
1665 * Creates an activity id for a given contact id
1667 * @param integer $cid Contact ID of target
1669 * @return bool|string activity id
1671 public static function activityIDFromContact($cid)
1673 $contact = DBA::selectFirst('contact', ['uid', 'id', 'created'], ['id' => $cid]);
1674 if (!DBA::isResult($contact)) {
1678 $hash = hash('ripemd128', $contact['uid'].'-'.$contact['id'].'-'.$contact['created']);
1679 $uuid = substr($hash, 0, 8). '-' . substr($hash, 8, 4) . '-' . substr($hash, 12, 4) . '-' . substr($hash, 16, 4) . '-' . substr($hash, 20, 12);
1680 return DI::baseUrl() . '/activity/' . $uuid;
1684 * Transmits a contact suggestion to a given inbox
1686 * @param integer $uid User ID
1687 * @param string $inbox Target inbox
1688 * @param integer $suggestion_id Suggestion ID
1690 * @return boolean was the transmission successful?
1691 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1693 public static function sendContactSuggestion($uid, $inbox, $suggestion_id)
1695 $owner = User::getOwnerDataById($uid);
1697 $suggestion = DI::fsuggest()->getById($suggestion_id);
1699 $data = ['@context' => ActivityPub::CONTEXT,
1700 'id' => DI::baseUrl() . '/activity/' . System::createGUID(),
1701 'type' => 'Announce',
1702 'actor' => $owner['url'],
1703 'object' => $suggestion->url,
1704 'content' => $suggestion->note,
1705 'instrument' => self::getService(),
1706 'to' => [ActivityPub::PUBLIC_COLLECTION],
1709 $signed = LDSignature::sign($data, $owner);
1711 Logger::log('Deliver profile deletion for user ' . $uid . ' to ' . $inbox . ' via ActivityPub', Logger::DEBUG);
1712 return HTTPSignature::transmit($signed, $inbox, $uid);
1716 * Transmits a profile relocation to a given inbox
1718 * @param integer $uid User ID
1719 * @param string $inbox Target inbox
1721 * @return boolean was the transmission successful?
1722 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1724 public static function sendProfileRelocation($uid, $inbox)
1726 $owner = User::getOwnerDataById($uid);
1728 $data = ['@context' => ActivityPub::CONTEXT,
1729 'id' => DI::baseUrl() . '/activity/' . System::createGUID(),
1730 'type' => 'dfrn:relocate',
1731 'actor' => $owner['url'],
1732 'object' => $owner['url'],
1733 'published' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
1734 'instrument' => self::getService(),
1735 'to' => [ActivityPub::PUBLIC_COLLECTION],
1738 $signed = LDSignature::sign($data, $owner);
1740 Logger::log('Deliver profile relocation for user ' . $uid . ' to ' . $inbox . ' via ActivityPub', Logger::DEBUG);
1741 return HTTPSignature::transmit($signed, $inbox, $uid);
1745 * Transmits a profile deletion to a given inbox
1747 * @param integer $uid User ID
1748 * @param string $inbox Target inbox
1750 * @return boolean was the transmission successful?
1751 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1753 public static function sendProfileDeletion($uid, $inbox)
1755 $owner = User::getOwnerDataById($uid);
1757 if (empty($owner)) {
1758 Logger::error('No owner data found, the deletion message cannot be processed.', ['user' => $uid]);
1762 if (empty($owner['uprvkey'])) {
1763 Logger::error('No private key for owner found, the deletion message cannot be processed.', ['user' => $uid]);
1767 $data = ['@context' => ActivityPub::CONTEXT,
1768 'id' => DI::baseUrl() . '/activity/' . System::createGUID(),
1770 'actor' => $owner['url'],
1771 'object' => $owner['url'],
1772 'published' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
1773 'instrument' => self::getService(),
1774 'to' => [ActivityPub::PUBLIC_COLLECTION],
1777 $signed = LDSignature::sign($data, $owner);
1779 Logger::log('Deliver profile deletion for user ' . $uid . ' to ' . $inbox . ' via ActivityPub', Logger::DEBUG);
1780 return HTTPSignature::transmit($signed, $inbox, $uid);
1784 * Transmits a profile change to a given inbox
1786 * @param integer $uid User ID
1787 * @param string $inbox Target inbox
1789 * @return boolean was the transmission successful?
1790 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1791 * @throws \ImagickException
1793 public static function sendProfileUpdate($uid, $inbox)
1795 $owner = User::getOwnerDataById($uid);
1796 $profile = APContact::getByURL($owner['url']);
1798 $data = ['@context' => ActivityPub::CONTEXT,
1799 'id' => DI::baseUrl() . '/activity/' . System::createGUID(),
1801 'actor' => $owner['url'],
1802 'object' => self::getProfile($uid),
1803 'published' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
1804 'instrument' => self::getService(),
1805 'to' => [$profile['followers']],
1808 $signed = LDSignature::sign($data, $owner);
1810 Logger::log('Deliver profile update for user ' . $uid . ' to ' . $inbox . ' via ActivityPub', Logger::DEBUG);
1811 return HTTPSignature::transmit($signed, $inbox, $uid);
1815 * Transmits a given activity to a target
1817 * @param string $activity Type name
1818 * @param string $target Target profile
1819 * @param integer $uid User ID
1821 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1822 * @throws \ImagickException
1823 * @throws \Exception
1825 public static function sendActivity($activity, $target, $uid, $id = '')
1827 $profile = APContact::getByURL($target);
1828 if (empty($profile['inbox'])) {
1829 Logger::warning('No inbox found for target', ['target' => $target, 'profile' => $profile]);
1833 $owner = User::getOwnerDataById($uid);
1836 $id = DI::baseUrl() . '/activity/' . System::createGUID();
1839 $data = ['@context' => ActivityPub::CONTEXT,
1841 'type' => $activity,
1842 'actor' => $owner['url'],
1843 'object' => $profile['url'],
1844 'instrument' => self::getService(),
1845 'to' => [$profile['url']]];
1847 Logger::log('Sending activity ' . $activity . ' to ' . $target . ' for user ' . $uid, Logger::DEBUG);
1849 $signed = LDSignature::sign($data, $owner);
1850 return HTTPSignature::transmit($signed, $profile['inbox'], $uid);
1854 * Transmits a "follow object" activity to a target
1855 * This is a preparation for sending automated "follow" requests when receiving "Announce" messages
1857 * @param string $object Object URL
1858 * @param string $target Target profile
1859 * @param integer $uid User ID
1861 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1862 * @throws \ImagickException
1863 * @throws \Exception
1865 public static function sendFollowObject($object, $target, $uid = 0)
1867 $profile = APContact::getByURL($target);
1868 if (empty($profile['inbox'])) {
1869 Logger::warning('No inbox found for target', ['target' => $target, 'profile' => $profile]);
1874 // Fetch the list of administrators
1875 $admin_mail = explode(',', str_replace(' ', '', DI::config()->get('config', 'admin_email')));
1877 // We need to use some user as a sender. It doesn't care who it will send. We will use an administrator account.
1878 $condition = ['verified' => true, 'blocked' => false, 'account_removed' => false, 'account_expired' => false, 'email' => $admin_mail];
1879 $first_user = DBA::selectFirst('user', ['uid'], $condition);
1880 $uid = $first_user['uid'];
1883 $condition = ['verb' => Activity::FOLLOW, 'uid' => 0, 'parent-uri' => $object,
1884 'author-id' => Contact::getPublicIdByUserId($uid)];
1885 if (Item::exists($condition)) {
1886 Logger::log('Follow for ' . $object . ' for user ' . $uid . ' does already exist.', Logger::DEBUG);
1890 $owner = User::getOwnerDataById($uid);
1892 $data = ['@context' => ActivityPub::CONTEXT,
1893 'id' => DI::baseUrl() . '/activity/' . System::createGUID(),
1895 'actor' => $owner['url'],
1896 'object' => $object,
1897 'instrument' => self::getService(),
1898 'to' => [$profile['url']]];
1900 Logger::log('Sending follow ' . $object . ' to ' . $target . ' for user ' . $uid, Logger::DEBUG);
1902 $signed = LDSignature::sign($data, $owner);
1903 return HTTPSignature::transmit($signed, $profile['inbox'], $uid);
1907 * Transmit a message that the contact request had been accepted
1909 * @param string $target Target profile
1911 * @param integer $uid User ID
1912 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1913 * @throws \ImagickException
1915 public static function sendContactAccept($target, $id, $uid)
1917 $profile = APContact::getByURL($target);
1918 if (empty($profile['inbox'])) {
1919 Logger::warning('No inbox found for target', ['target' => $target, 'profile' => $profile]);
1923 $owner = User::getOwnerDataById($uid);
1924 $data = ['@context' => ActivityPub::CONTEXT,
1925 'id' => DI::baseUrl() . '/activity/' . System::createGUID(),
1927 'actor' => $owner['url'],
1929 'id' => (string)$id,
1931 'actor' => $profile['url'],
1932 'object' => $owner['url']
1934 'instrument' => self::getService(),
1935 'to' => [$profile['url']]];
1937 Logger::debug('Sending accept to ' . $target . ' for user ' . $uid . ' with id ' . $id);
1939 $signed = LDSignature::sign($data, $owner);
1940 HTTPSignature::transmit($signed, $profile['inbox'], $uid);
1944 * Reject a contact request or terminates the contact relation
1946 * @param string $target Target profile
1948 * @param integer $uid User ID
1949 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1950 * @throws \ImagickException
1952 public static function sendContactReject($target, $id, $uid)
1954 $profile = APContact::getByURL($target);
1955 if (empty($profile['inbox'])) {
1956 Logger::warning('No inbox found for target', ['target' => $target, 'profile' => $profile]);
1960 $owner = User::getOwnerDataById($uid);
1961 $data = ['@context' => ActivityPub::CONTEXT,
1962 'id' => DI::baseUrl() . '/activity/' . System::createGUID(),
1964 'actor' => $owner['url'],
1966 'id' => (string)$id,
1968 'actor' => $profile['url'],
1969 'object' => $owner['url']
1971 'instrument' => self::getService(),
1972 'to' => [$profile['url']]];
1974 Logger::debug('Sending reject to ' . $target . ' for user ' . $uid . ' with id ' . $id);
1976 $signed = LDSignature::sign($data, $owner);
1977 HTTPSignature::transmit($signed, $profile['inbox'], $uid);
1981 * Transmits a message that we don't want to follow this contact anymore
1983 * @param string $target Target profile
1984 * @param integer $uid User ID
1985 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1986 * @throws \ImagickException
1987 * @throws \Exception
1988 * @return bool success
1990 public static function sendContactUndo($target, $cid, $uid)
1992 $profile = APContact::getByURL($target);
1993 if (empty($profile['inbox'])) {
1994 Logger::warning('No inbox found for target', ['target' => $target, 'profile' => $profile]);
1998 $object_id = self::activityIDFromContact($cid);
1999 if (empty($object_id)) {
2003 $id = DI::baseUrl() . '/activity/' . System::createGUID();
2005 $owner = User::getOwnerDataById($uid);
2006 $data = ['@context' => ActivityPub::CONTEXT,
2009 'actor' => $owner['url'],
2010 'object' => ['id' => $object_id, 'type' => 'Follow',
2011 'actor' => $owner['url'],
2012 'object' => $profile['url']],
2013 'instrument' => self::getService(),
2014 'to' => [$profile['url']]];
2016 Logger::log('Sending undo to ' . $target . ' for user ' . $uid . ' with id ' . $id, Logger::DEBUG);
2018 $signed = LDSignature::sign($data, $owner);
2019 return HTTPSignature::transmit($signed, $profile['inbox'], $uid);
2022 private static function prependMentions($body, int $uriid)
2026 foreach (Tag::getByURIId($uriid, [Tag::IMPLICIT_MENTION]) as $tag) {
2027 $profile = Contact::getByURL($tag['url'], false, ['addr', 'contact-type', 'nick']);
2028 if (!empty($profile['addr'])
2029 && $profile['contact-type'] != Contact::TYPE_COMMUNITY
2030 && !strstr($body, $profile['addr'])
2031 && !strstr($body, $tag['url'])
2033 $mentions[] = '@[url=' . $tag['url'] . ']' . $profile['nick'] . '[/url]';
2037 $mentions[] = $body;
2039 return implode(' ', $mentions);