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\Util\DateTimeFormat;
46 use Friendica\Util\HTTPSignature;
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'],
152 $condition = DBA::buildCondition($parameters);
154 $sql = "SELECT COUNT(*) as `count`
156 JOIN `apcontact` ON `apcontact`.`url` = `contact`.`url`
159 $contacts = DBA::fetchFirst($sql, ...$parameters);
161 $modulePath = '/' . $module . '/';
163 $data = ['@context' => ActivityPub::CONTEXT];
164 $data['id'] = DI::baseUrl() . $modulePath . $owner['nickname'];
165 $data['type'] = 'OrderedCollection';
166 $data['totalItems'] = $contacts['count'];
168 // When we hide our friends we will only show the pure number but don't allow more.
169 $profile = Profile::getByUID($owner['uid']);
170 if (!empty($profile['hide-friends'])) {
175 $data['first'] = DI::baseUrl() . $modulePath . $owner['nickname'] . '?page=1';
177 $data['type'] = 'OrderedCollectionPage';
180 $sql = "SELECT `contact`.`url`
182 JOIN `apcontact` ON `apcontact`.`url` = `contact`.`url`
186 $parameters[] = ($page - 1) * 100;
189 $contacts = DBA::p($sql, ...$parameters);
190 while ($contact = DBA::fetch($contacts)) {
191 $list[] = $contact['url'];
193 DBA::close($contacts);
196 $data['next'] = DI::baseUrl() . $modulePath . $owner['nickname'] . '?page=' . ($page + 1);
199 $data['partOf'] = DI::baseUrl() . $modulePath . $owner['nickname'];
201 $data['orderedItems'] = $list;
208 * Public posts for the given owner
210 * @param array $owner Owner array
211 * @param integer $page Page number
212 * @param string $requester URL of requesting account
214 * @return array of posts
215 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
216 * @throws \ImagickException
218 public static function getOutbox($owner, $page = null, $requester = '')
220 $public_contact = Contact::getIdForURL($owner['url']);
221 $condition = ['uid' => 0, 'contact-id' => $public_contact,
222 'private' => [Item::PUBLIC, Item::UNLISTED]];
224 if (!empty($requester)) {
225 $requester_id = Contact::getIdForURL($requester, $owner['uid']);
226 if (!empty($requester_id)) {
227 $permissionSets = DI::permissionSet()->selectByContactId($requester_id, $owner['uid']);
228 if (!empty($permissionSets)) {
229 $condition = ['uid' => $owner['uid'], 'origin' => true,
230 'psid' => array_merge($permissionSets->column('id'),
231 [DI::permissionSet()->getIdFromACL($owner['uid'], '', '', '', '')])];
236 $condition = array_merge($condition,
237 ['author-id' => $public_contact,
238 'gravity' => [GRAVITY_PARENT, GRAVITY_COMMENT],
239 'deleted' => false, 'visible' => true, 'moderated' => false]);
241 $count = DBA::count('item', $condition);
243 $data = ['@context' => ActivityPub::CONTEXT];
244 $data['id'] = DI::baseUrl() . '/outbox/' . $owner['nickname'];
245 $data['type'] = 'OrderedCollection';
246 $data['totalItems'] = $count;
249 $data['first'] = DI::baseUrl() . '/outbox/' . $owner['nickname'] . '?page=1';
251 $data['type'] = 'OrderedCollectionPage';
254 $condition['parent-network'] = Protocol::NATIVE_SUPPORT;
256 $items = Item::select(['id'], $condition, ['limit' => [($page - 1) * 20, 20], 'order' => ['created' => true]]);
257 while ($item = Item::fetch($items)) {
258 $activity = self::createActivityFromItem($item['id'], true);
259 $activity['type'] = $activity['type'] == 'Update' ? 'Create' : $activity['type'];
261 // Only list "Create" activity objects here, no reshares
262 if (!empty($activity['object']) && ($activity['type'] == 'Create')) {
263 $list[] = $activity['object'];
268 $data['next'] = DI::baseUrl() . '/outbox/' . $owner['nickname'] . '?page=' . ($page + 1);
271 $data['partOf'] = DI::baseUrl() . '/outbox/' . $owner['nickname'];
273 $data['orderedItems'] = $list;
280 * Return the service array containing information the used software and it's url
282 * @return array with service data
284 private static function getService()
286 return ['type' => 'Service',
287 'name' => FRIENDICA_PLATFORM . " '" . FRIENDICA_CODENAME . "' " . FRIENDICA_VERSION . '-' . DB_UPDATE_VERSION,
288 'url' => DI::baseUrl()->get()];
292 * Return the ActivityPub profile of the given user
294 * @param integer $uid User ID
295 * @return array with profile data
296 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
298 public static function getProfile($uid)
301 $condition = ['uid' => $uid, 'blocked' => false, 'account_expired' => false,
302 'account_removed' => false, 'verified' => true];
303 $fields = ['guid', 'nickname', 'pubkey', 'account-type', 'page-flags'];
304 $user = DBA::selectFirst('user', $fields, $condition);
305 if (!DBA::isResult($user)) {
309 $fields = ['locality', 'region', 'country-name'];
310 $profile = DBA::selectFirst('profile', $fields, ['uid' => $uid]);
311 if (!DBA::isResult($profile)) {
315 $fields = ['name', 'url', 'location', 'about', 'avatar', 'photo'];
316 $contact = DBA::selectFirst('contact', $fields, ['uid' => $uid, 'self' => true]);
317 if (!DBA::isResult($contact)) {
321 $contact = User::getSystemAccount();
322 $user = ['guid' => '', 'nickname' => $contact['nick'], 'pubkey' => $contact['pubkey'],
323 'account-type' => $contact['contact-type'], 'page-flags' => User::PAGE_FLAGS_NORMAL];
324 $profile = ['locality' => '', 'region' => '', 'country-name' => ''];
327 $data = ['@context' => ActivityPub::CONTEXT];
328 $data['id'] = $contact['url'];
330 if (!empty($user['guid'])) {
331 $data['diaspora:guid'] = $user['guid'];
334 $data['type'] = ActivityPub::ACCOUNT_TYPES[$user['account-type']];
337 $data['following'] = DI::baseUrl() . '/following/' . $user['nickname'];
338 $data['followers'] = DI::baseUrl() . '/followers/' . $user['nickname'];
339 $data['inbox'] = DI::baseUrl() . '/inbox/' . $user['nickname'];
340 $data['outbox'] = DI::baseUrl() . '/outbox/' . $user['nickname'];
342 $data['inbox'] = DI::baseUrl() . '/friendica/inbox';
345 $data['preferredUsername'] = $user['nickname'];
346 $data['name'] = $contact['name'];
348 if (!empty($profile['country-name'] . $profile['region'] . $profile['locality'])) {
349 $data['vcard:hasAddress'] = ['@type' => 'vcard:Home', 'vcard:country-name' => $profile['country-name'],
350 'vcard:region' => $profile['region'], 'vcard:locality' => $profile['locality']];
353 if (!empty($contact['about'])) {
354 $data['summary'] = BBCode::convert($contact['about'], false);
357 $data['url'] = $contact['url'];
358 $data['manuallyApprovesFollowers'] = in_array($user['page-flags'], [User::PAGE_FLAGS_NORMAL, User::PAGE_FLAGS_PRVGROUP]);
359 $data['publicKey'] = ['id' => $contact['url'] . '#main-key',
360 'owner' => $contact['url'],
361 'publicKeyPem' => $user['pubkey']];
362 $data['endpoints'] = ['sharedInbox' => DI::baseUrl() . '/inbox'];
363 $data['icon'] = ['type' => 'Image',
364 'url' => $contact['photo']];
366 $data['generator'] = self::getService();
368 // tags: https://kitty.town/@inmysocks/100656097926961126.json
373 * @param string $username
375 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
377 public static function getDeletedUser($username)
380 '@context' => ActivityPub::CONTEXT,
381 'id' => DI::baseUrl() . '/profile/' . $username,
382 'type' => 'Tombstone',
383 'published' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
384 'updated' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
385 'deleted' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
390 * Returns an array with permissions of a given item array
394 * @return array with permissions
395 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
396 * @throws \ImagickException
398 private static function fetchPermissionBlockFromConversation($item)
400 if (empty($item['thr-parent'])) {
404 $condition = ['item-uri' => $item['thr-parent'], 'protocol' => Conversation::PARCEL_ACTIVITYPUB];
405 $conversation = DBA::selectFirst('conversation', ['source'], $condition);
406 if (!DBA::isResult($conversation)) {
410 $activity = json_decode($conversation['source'], true);
412 $actor = JsonLD::fetchElement($activity, 'actor', 'id');
413 $profile = APContact::getByURL($actor);
415 $item_profile = APContact::getByURL($item['author-link']);
416 $exclude[] = $item['author-link'];
418 if ($item['gravity'] == GRAVITY_PARENT) {
419 $exclude[] = $item['owner-link'];
422 $permissions['to'][] = $actor;
424 foreach (['to', 'cc', 'bto', 'bcc'] as $element) {
425 if (empty($activity[$element])) {
428 if (is_string($activity[$element])) {
429 $activity[$element] = [$activity[$element]];
432 foreach ($activity[$element] as $receiver) {
433 if (empty($receiver)) {
437 if (!empty($profile['followers']) && $receiver == $profile['followers'] && !empty($item_profile['followers'])) {
438 $permissions[$element][] = $item_profile['followers'];
439 } elseif (!in_array($receiver, $exclude)) {
440 $permissions[$element][] = $receiver;
448 * Creates an array of permissions from an item thread
450 * @param array $item Item array
451 * @param boolean $blindcopy addressing via "bcc" or "cc"?
452 * @param integer $last_id Last item id for adding receivers
453 * @param boolean $forum_mode "true" means that we are sending content to a forum
455 * @return array with permission data
456 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
457 * @throws \ImagickException
459 private static function createPermissionBlockForItem($item, $blindcopy, $last_id = 0, $forum_mode = false)
462 $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'];
475 if (DI::config()->get('system', 'ap_always_bcc')) {
479 if (self::isAnnounce($item) || DI::config()->get('debug', 'total_ap_delivery')) {
480 // Will be activated in a later step
481 $networks = Protocol::FEDERATED;
483 // For now only send to these contacts:
484 $networks = [Protocol::ACTIVITYPUB, Protocol::OSTATUS];
487 $data = ['to' => [], 'cc' => [], 'bcc' => []];
489 if ($item['gravity'] == GRAVITY_PARENT) {
490 $actor_profile = APContact::getByURL($item['owner-link']);
492 $actor_profile = APContact::getByURL($item['author-link']);
495 $terms = Tag::getByURIId($item['uri-id'], [Tag::MENTION, Tag::IMPLICIT_MENTION, Tag::EXCLUSIVE_MENTION]);
497 if ($item['private'] != Item::PRIVATE) {
498 // Directly mention the original author upon a quoted reshare.
499 // Else just ensure that the original author receives the reshare.
500 $announce = self::getAnnounceArray($item);
501 if (!empty($announce['comment'])) {
502 $data['to'][] = $announce['actor']['url'];
503 } elseif (!empty($announce)) {
504 $data['cc'][] = $announce['actor']['url'];
507 $data = array_merge($data, self::fetchPermissionBlockFromConversation($item));
509 // Check if the item is completely public or unlisted
510 if ($item['private'] == Item::PUBLIC) {
511 $data['to'][] = ActivityPub::PUBLIC_COLLECTION;
513 $data['cc'][] = ActivityPub::PUBLIC_COLLECTION;
516 foreach ($terms as $term) {
517 $profile = APContact::getByURL($term['url'], false);
518 if (!empty($profile)) {
519 $data['to'][] = $profile['url'];
523 $receiver_list = Item::enumeratePermissions($item, true);
525 foreach ($terms as $term) {
526 $cid = Contact::getIdForURL($term['url'], $item['uid']);
527 if (!empty($cid) && in_array($cid, $receiver_list)) {
528 $contact = DBA::selectFirst('contact', ['url', 'network', 'protocol'], ['id' => $cid]);
529 if (!DBA::isResult($contact) || (!in_array($contact['network'], $networks) && ($contact['protocol'] != Protocol::ACTIVITYPUB))) {
533 if (!empty($profile = APContact::getByURL($contact['url'], false))) {
534 $data['to'][] = $profile['url'];
539 foreach ($receiver_list as $receiver) {
540 $contact = DBA::selectFirst('contact', ['url', 'hidden', 'network', 'protocol'], ['id' => $receiver]);
541 if (!DBA::isResult($contact) || (!in_array($contact['network'], $networks) && ($contact['protocol'] != Protocol::ACTIVITYPUB))) {
545 if (!empty($profile = APContact::getByURL($contact['url'], false))) {
546 if ($contact['hidden'] || $always_bcc) {
547 $data['bcc'][] = $profile['url'];
549 $data['cc'][] = $profile['url'];
555 if (!empty($item['parent'])) {
556 $parents = Item::select(['id', 'author-link', 'owner-link', 'gravity', 'uri'], ['parent' => $item['parent']]);
557 while ($parent = Item::fetch($parents)) {
558 if ($parent['gravity'] == GRAVITY_PARENT) {
559 $profile = APContact::getByURL($parent['owner-link'], false);
560 if (!empty($profile)) {
561 if ($item['gravity'] != GRAVITY_PARENT) {
562 // Comments to forums are directed to the forum
563 // But comments to forums aren't directed to the followers collection
564 // This rule is only valid when the actor isn't the forum.
565 // The forum needs to transmit their content to their followers.
566 if (($profile['type'] == 'Group') && ($profile['url'] != $actor_profile['url'])) {
567 $data['to'][] = $profile['url'];
569 $data['cc'][] = $profile['url'];
570 if (($item['private'] != Item::PRIVATE) && !empty($actor_profile['followers'])) {
571 $data['cc'][] = $actor_profile['followers'];
575 // Public thread parent post always are directed to the followers
576 if (($item['private'] != Item::PRIVATE) && !$forum_mode) {
577 $data['cc'][] = $actor_profile['followers'];
583 // Don't include data from future posts
584 if ($parent['id'] >= $last_id) {
588 $profile = APContact::getByURL($parent['author-link'], false);
589 if (!empty($profile)) {
590 if (($profile['type'] == 'Group') || ($parent['uri'] == $item['thr-parent'])) {
591 $data['to'][] = $profile['url'];
593 $data['cc'][] = $profile['url'];
597 DBA::close($parents);
600 $data['to'] = array_unique($data['to']);
601 $data['cc'] = array_unique($data['cc']);
602 $data['bcc'] = array_unique($data['bcc']);
604 if (($key = array_search($item['author-link'], $data['to'])) !== false) {
605 unset($data['to'][$key]);
608 if (($key = array_search($item['author-link'], $data['cc'])) !== false) {
609 unset($data['cc'][$key]);
612 if (($key = array_search($item['author-link'], $data['bcc'])) !== false) {
613 unset($data['bcc'][$key]);
616 foreach ($data['to'] as $to) {
617 if (($key = array_search($to, $data['cc'])) !== false) {
618 unset($data['cc'][$key]);
621 if (($key = array_search($to, $data['bcc'])) !== false) {
622 unset($data['bcc'][$key]);
626 foreach ($data['cc'] as $cc) {
627 if (($key = array_search($cc, $data['bcc'])) !== false) {
628 unset($data['bcc'][$key]);
632 $receivers = ['to' => array_values($data['to']), 'cc' => array_values($data['cc']), 'bcc' => array_values($data['bcc'])];
635 unset($receivers['bcc']);
642 * Check if an inbox is archived
644 * @param string $url Inbox url
646 * @return boolean "true" if inbox is archived
648 private static function archivedInbox($url)
650 return DBA::exists('inbox-status', ['url' => $url, 'archive' => true]);
654 * Fetches a list of inboxes of followers of a given user
656 * @param integer $uid User ID
657 * @param boolean $personal fetch personal inboxes
659 * @return array of follower inboxes
660 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
661 * @throws \ImagickException
663 public static function fetchTargetInboxesforUser($uid, $personal = false)
669 if (!empty($item['uid'])) {
670 $profile = User::getOwnerDataById($item['uid']);
671 if (!empty($profile)) {
672 $isforum = $profile['account-type'] == User::ACCOUNT_TYPE_COMMUNITY;
676 if (DI::config()->get('debug', 'total_ap_delivery')) {
677 // Will be activated in a later step
678 $networks = Protocol::FEDERATED;
680 // For now only send to these contacts:
681 $networks = [Protocol::ACTIVITYPUB, Protocol::OSTATUS];
684 $condition = ['uid' => $uid, 'archive' => false, 'pending' => false, 'blocked' => false];
687 $condition['rel'] = [Contact::FOLLOWER, Contact::FRIEND];
690 $contacts = DBA::select('contact', ['url', 'network', 'protocol'], $condition);
691 while ($contact = DBA::fetch($contacts)) {
692 if (Contact::isLocal($contact['url'])) {
696 if (!in_array($contact['network'], $networks) && ($contact['protocol'] != Protocol::ACTIVITYPUB)) {
700 if ($isforum && ($contact['dfrn'] == Protocol::DFRN)) {
704 if (Network::isUrlBlocked($contact['url'])) {
708 $profile = APContact::getByURL($contact['url'], false);
709 if (!empty($profile)) {
710 if (empty($profile['sharedinbox']) || $personal) {
711 $target = $profile['inbox'];
713 $target = $profile['sharedinbox'];
715 if (!self::archivedInbox($target)) {
716 $inboxes[$target] = $target;
720 DBA::close($contacts);
726 * Fetches an array of inboxes for the given item and user
728 * @param array $item Item array
729 * @param integer $uid User ID
730 * @param boolean $personal fetch personal inboxes
731 * @param integer $last_id Last item id for adding receivers
732 * @param boolean $forum_mode "true" means that we are sending content to a forum
733 * @return array with inboxes
734 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
735 * @throws \ImagickException
737 public static function fetchTargetInboxes($item, $uid, $personal = false, $last_id = 0, $forum_mode = false)
739 $permissions = self::createPermissionBlockForItem($item, true, $last_id, $forum_mode);
740 if (empty($permissions)) {
746 if ($item['gravity'] == GRAVITY_ACTIVITY) {
747 $item_profile = APContact::getByURL($item['author-link'], false);
749 $item_profile = APContact::getByURL($item['owner-link'], false);
752 if (empty($item_profile)) {
756 $profile_uid = User::getIdForURL($item_profile['url']);
758 foreach (['to', 'cc', 'bto', 'bcc'] as $element) {
759 if (empty($permissions[$element])) {
763 $blindcopy = in_array($element, ['bto', 'bcc']);
765 foreach ($permissions[$element] as $receiver) {
766 if (empty($receiver) || Network::isUrlBlocked($receiver)) {
770 if ($item_profile && ($receiver == $item_profile['followers']) && ($uid == $profile_uid)) {
771 $inboxes = array_merge($inboxes, self::fetchTargetInboxesforUser($uid, $personal));
773 if (Contact::isLocal($receiver)) {
777 $profile = APContact::getByURL($receiver, false);
778 if (!empty($profile)) {
779 if (empty($profile['sharedinbox']) || $personal || $blindcopy) {
780 $target = $profile['inbox'];
782 $target = $profile['sharedinbox'];
784 if (!self::archivedInbox($target)) {
785 $inboxes[$target] = $target;
796 * Creates an array in the structure of the item table for a given mail id
798 * @param integer $mail_id
803 public static function ItemArrayFromMail($mail_id)
805 $mail = DBA::selectFirst('mail', [], ['id' => $mail_id]);
806 if (!DBA::isResult($mail)) {
810 $mail['uri-id'] = ItemURI::insert(['uri' => $mail['uri'], 'guid' => $mail['guid']]);
812 $reply = DBA::selectFirst('mail', ['uri'], ['parent-uri' => $mail['parent-uri'], 'reply' => false]);
814 // Making the post more compatible for Mastodon by:
815 // - Making it a note and not an article (no title)
816 // - Moving the title into the "summary" field that is used as a "content warning"
817 $mail['body'] = '[abstract]' . $mail['title'] . "[/abstract]\n" . $mail['body'];
820 $mail['author-link'] = $mail['owner-link'] = $mail['from-url'];
821 $mail['allow_cid'] = '<'.$mail['contact-id'].'>';
822 $mail['allow_gid'] = '';
823 $mail['deny_cid'] = '';
824 $mail['deny_gid'] = '';
825 $mail['private'] = true;
826 $mail['deleted'] = false;
827 $mail['edited'] = $mail['created'];
828 $mail['plink'] = $mail['uri'];
829 $mail['thr-parent'] = $reply['uri'];
830 $mail['gravity'] = ($mail['reply'] ? GRAVITY_COMMENT: GRAVITY_PARENT);
832 $mail['event-type'] = '';
840 * Creates an activity array for a given mail id
842 * @param integer $mail_id
843 * @param boolean $object_mode Is the activity item is used inside another object?
845 * @return array of activity
848 public static function createActivityFromMail($mail_id, $object_mode = false)
850 $mail = self::ItemArrayFromMail($mail_id);
854 $object = self::createNote($mail);
857 $data = ['@context' => ActivityPub::CONTEXT];
862 $data['id'] = $mail['uri'] . '/Create';
863 $data['type'] = 'Create';
864 $data['actor'] = $mail['author-link'];
865 $data['published'] = DateTimeFormat::utc($mail['created'] . '+00:00', DateTimeFormat::ATOM);
866 $data['instrument'] = self::getService();
867 $data = array_merge($data, self::createPermissionBlockForItem($mail, true));
869 if (empty($data['to']) && !empty($data['cc'])) {
870 $data['to'] = $data['cc'];
873 if (empty($data['to']) && !empty($data['bcc'])) {
874 $data['to'] = $data['bcc'];
880 $object['to'] = $data['to'];
881 $object['tag'] = [['type' => 'Mention', 'href' => $object['to'][0], 'name' => '']];
883 unset($object['cc']);
884 unset($object['bcc']);
886 $data['directMessage'] = true;
888 $data['object'] = $object;
890 $owner = User::getOwnerDataById($mail['uid']);
892 if (!$object_mode && !empty($owner)) {
893 return LDSignature::sign($data, $owner);
900 * Returns the activity type of a given item
904 * @return string with activity type
905 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
906 * @throws \ImagickException
908 private static function getTypeOfItem($item)
912 // Only check for a reshare, if it is a real reshare and no quoted reshare
913 if (strpos($item['body'], "[share") === 0) {
914 $announce = self::getAnnounceArray($item);
915 $reshared = !empty($announce);
920 } elseif ($item['verb'] == Activity::POST) {
921 if ($item['created'] == $item['edited']) {
926 } elseif ($item['verb'] == Activity::LIKE) {
928 } elseif ($item['verb'] == Activity::DISLIKE) {
930 } elseif ($item['verb'] == Activity::ATTEND) {
932 } elseif ($item['verb'] == Activity::ATTENDNO) {
934 } elseif ($item['verb'] == Activity::ATTENDMAYBE) {
935 $type = 'TentativeAccept';
936 } elseif ($item['verb'] == Activity::FOLLOW) {
938 } elseif ($item['verb'] == Activity::TAG) {
940 } elseif ($item['verb'] == Activity::ANNOUNCE) {
950 * Creates the activity or fetches it from the cache
952 * @param integer $item_id
953 * @param boolean $force Force new cache entry
955 * @return array with the activity
958 public static function createCachedActivityFromItem($item_id, $force = false)
960 $cachekey = 'APDelivery:createActivity:' . $item_id;
963 $data = DI::cache()->get($cachekey);
964 if (!is_null($data)) {
969 $data = self::createActivityFromItem($item_id);
971 DI::cache()->set($cachekey, $data, Duration::QUARTER_HOUR);
976 * Creates an activity array for a given item id
978 * @param integer $item_id
979 * @param boolean $object_mode Is the activity item is used inside another object?
981 * @return array of activity
984 public static function createActivityFromItem($item_id, $object_mode = false)
986 Logger::info('Fetching activity', ['item' => $item_id]);
987 $item = Item::selectFirst([], ['id' => $item_id, 'parent-network' => Protocol::NATIVE_SUPPORT]);
988 if (!DBA::isResult($item)) {
992 // In case of a forum post ensure to return the original post if author and forum are on the same machine
993 if (!empty($item['forum_mode'])) {
994 $author = Contact::getById($item['author-id'], ['nurl']);
995 if (!empty($author['nurl'])) {
996 $self = Contact::selectFirst(['uid'], ['nurl' => $author['nurl'], 'self' => true]);
997 if (!empty($self['uid'])) {
998 $forum_item = Item::selectFirst([], ['uri-id' => $item['uri-id'], 'uid' => $self['uid']]);
999 if (DBA::isResult($item)) {
1000 $item = $forum_item;
1006 if (empty($item['uri-id'])) {
1007 Logger::warning('Item without uri-id', ['item' => $item]);
1012 $condition = ['item-uri' => $item['uri'], 'protocol' => Conversation::PARCEL_ACTIVITYPUB];
1013 $conversation = DBA::selectFirst('conversation', ['source'], $condition);
1014 if (DBA::isResult($conversation)) {
1015 $data = json_decode($conversation['source'], true);
1016 if (!empty($data['type'])) {
1017 if (in_array($data['type'], ['Create', 'Update'])) {
1019 unset($data['@context']);
1020 unset($data['signature']);
1022 Logger::info('Return stored conversation', ['item' => $item_id]);
1024 } elseif (in_array('as:' . $data['type'], Receiver::CONTENT_TYPES)) {
1025 if (!empty($data['@context'])) {
1026 $context = $data['@context'];
1027 unset($data['@context']);
1029 unset($data['actor']);
1035 $type = self::getTypeOfItem($item);
1038 if (!$object_mode) {
1039 $data = ['@context' => $context ?? ActivityPub::CONTEXT];
1041 if ($item['deleted'] && ($item['gravity'] == GRAVITY_ACTIVITY)) {
1043 } elseif ($item['deleted']) {
1050 if (($item['gravity'] == GRAVITY_ACTIVITY) && ($type != 'Undo')) {
1051 $data['id'] = $item['uri'];
1053 $data['id'] = $item['uri'] . '/' . $type;
1056 $data['type'] = $type;
1058 if (($type != 'Announce') || ($item['gravity'] != GRAVITY_PARENT)) {
1059 $data['actor'] = $item['author-link'];
1061 $data['actor'] = $item['owner-link'];
1064 $data['published'] = DateTimeFormat::utc($item['created'] . '+00:00', DateTimeFormat::ATOM);
1066 $data['instrument'] = self::getService();
1068 $data = array_merge($data, self::createPermissionBlockForItem($item, false));
1070 if (in_array($data['type'], ['Create', 'Update', 'Delete'])) {
1071 $data['object'] = $object ?? self::createNote($item);
1072 } elseif ($data['type'] == 'Add') {
1073 $data = self::createAddTag($item, $data);
1074 } elseif ($data['type'] == 'Announce') {
1075 if ($item['verb'] == ACTIVITY::ANNOUNCE) {
1076 $data['object'] = $item['thr-parent'];
1078 $data = self::createAnnounce($item, $data);
1080 } elseif ($data['type'] == 'Follow') {
1081 $data['object'] = $item['parent-uri'];
1082 } elseif ($data['type'] == 'Undo') {
1083 $data['object'] = self::createActivityFromItem($item_id, true);
1085 $data['diaspora:guid'] = $item['guid'];
1086 if (!empty($item['signed_text'])) {
1087 $data['diaspora:like'] = $item['signed_text'];
1089 $data['object'] = $item['thr-parent'];
1092 if (!empty($item['contact-uid'])) {
1093 $uid = $item['contact-uid'];
1095 $uid = $item['uid'];
1098 $owner = User::getOwnerDataById($uid);
1100 Logger::info('Fetched activity', ['item' => $item_id, 'uid' => $uid]);
1102 // We don't sign if we aren't the actor. This is important for relaying content especially for forums
1103 if (!$object_mode && !empty($owner) && ($data['actor'] == $owner['url'])) {
1104 return LDSignature::sign($data, $owner);
1109 /// @todo Create "conversation" entry
1113 * Creates a location entry for a given item array
1115 * @param array $item
1117 * @return array with location array
1119 private static function createLocation($item)
1121 $location = ['type' => 'Place'];
1123 if (!empty($item['location'])) {
1124 $location['name'] = $item['location'];
1129 if (empty($item['coord'])) {
1130 $coord = Map::getCoordinates($item['location']);
1132 $coords = explode(' ', $item['coord']);
1133 if (count($coords) == 2) {
1134 $coord = ['lat' => $coords[0], 'lon' => $coords[1]];
1138 if (!empty($coord['lat']) && !empty($coord['lon'])) {
1139 $location['latitude'] = $coord['lat'];
1140 $location['longitude'] = $coord['lon'];
1147 * Returns a tag array for a given item array
1149 * @param array $item
1151 * @return array of tags
1152 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1154 private static function createTagList($item)
1158 $terms = Tag::getByURIId($item['uri-id'], [Tag::HASHTAG, Tag::MENTION, Tag::IMPLICIT_MENTION, Tag::EXCLUSIVE_MENTION]);
1159 foreach ($terms as $term) {
1160 if ($term['type'] == Tag::HASHTAG) {
1161 $url = DI::baseUrl() . '/search?tag=' . urlencode($term['name']);
1162 $tags[] = ['type' => 'Hashtag', 'href' => $url, 'name' => '#' . $term['name']];
1164 $contact = Contact::getByURL($term['url'], false, ['addr']);
1165 if (empty($contact)) {
1168 if (!empty($contact['addr'])) {
1169 $mention = '@' . $contact['addr'];
1171 $mention = '@' . $term['url'];
1174 $tags[] = ['type' => 'Mention', 'href' => $term['url'], 'name' => $mention];
1178 $announce = self::getAnnounceArray($item);
1179 // Mention the original author upon commented reshares
1180 if (!empty($announce['comment'])) {
1181 $tags[] = ['type' => 'Mention', 'href' => $announce['actor']['url'], 'name' => '@' . $announce['actor']['addr']];
1188 * Adds attachment data to the JSON document
1190 * @param array $item Data of the item that is to be posted
1191 * @param string $type Object type
1193 * @return array with attachment data
1194 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1196 private static function createAttachmentList($item, $type)
1200 // Currently deactivated, since it creates side effects on Mastodon and Pleroma.
1201 // It will be reactivated, once this cleared.
1203 $attach_data = BBCode::getAttachmentData($item['body']);
1204 if (!empty($attach_data['url'])) {
1205 $attachment = ['type' => 'Page',
1206 'mediaType' => 'text/html',
1207 'url' => $attach_data['url']];
1209 if (!empty($attach_data['title'])) {
1210 $attachment['name'] = $attach_data['title'];
1213 if (!empty($attach_data['description'])) {
1214 $attachment['summary'] = $attach_data['description'];
1217 if (!empty($attach_data['image'])) {
1218 $imgdata = Images::getInfoFromURLCached($attach_data['image']);
1220 $attachment['icon'] = ['type' => 'Image',
1221 'mediaType' => $imgdata['mime'],
1222 'width' => $imgdata[0],
1223 'height' => $imgdata[1],
1224 'url' => $attach_data['image']];
1228 $attachments[] = $attachment;
1231 foreach (Post\Media::getByURIId($item['uri-id'], [Post\Media::DOCUMENT, Post\Media::TORRENT, Post\Media::UNKNOWN]) as $attachment) {
1232 $attachments[] = ['type' => 'Document',
1233 'mediaType' => $attachment['mimetype'],
1234 'url' => $attachment['url'],
1235 'name' => $attachment['description']];
1238 if ($type != 'Note') {
1239 return $attachments;
1242 foreach (Post\Media::getByURIId($item['uri-id'], [Post\Media::AUDIO, Post\Media::IMAGE, Post\Media::VIDEO]) as $attachment) {
1243 $attachments[] = ['type' => 'Document',
1244 'mediaType' => $attachment['mimetype'],
1245 'url' => $attachment['url'],
1246 'name' => $attachment['description']];
1249 return $attachments;
1253 * Callback function to replace a Friendica style mention in a mention that is used on AP
1255 * @param array $match Matching values for the callback
1256 * @return string Replaced mention
1257 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1259 private static function mentionCallback($match)
1261 if (empty($match[1])) {
1265 $data = Contact::getByURL($match[1], false, ['url', 'alias', 'nick']);
1266 if (empty($data['nick'])) {
1270 return '[url=' . ($data['alias'] ?: $data['url']) . ']@' . $data['nick'] . '[/url]';
1274 * Remove image elements since they are added as attachment
1276 * @param string $body
1278 * @return string with removed images
1280 private static function removePictures($body)
1282 // Simplify image codes
1283 $body = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '[img]$3[/img]', $body);
1284 $body = preg_replace("/\[img\=(.*?)\](.*?)\[\/img\]/ism", '[img]$1[/img]', $body);
1286 // Now remove local links
1287 $body = preg_replace_callback(
1288 '/\[url=([^\[\]]*)\]\[img\](.*)\[\/img\]\[\/url\]/Usi',
1290 // We remove the link when it is a link to a local photo page
1291 if (Photo::isLocalPage($match[1])) {
1294 // otherwise we just return the link
1295 return '[url]' . $match[1] . '[/url]';
1300 // Remove all pictures
1301 $body = preg_replace("/\[img\]([^\[\]]*)\[\/img\]/Usi", '', $body);
1307 * Fetches the "context" value for a givem item array from the "conversation" table
1309 * @param array $item
1311 * @return string with context url
1312 * @throws \Exception
1314 private static function fetchContextURLForItem($item)
1316 $conversation = DBA::selectFirst('conversation', ['conversation-href', 'conversation-uri'], ['item-uri' => $item['parent-uri']]);
1317 if (DBA::isResult($conversation) && !empty($conversation['conversation-href'])) {
1318 $context_uri = $conversation['conversation-href'];
1319 } elseif (DBA::isResult($conversation) && !empty($conversation['conversation-uri'])) {
1320 $context_uri = $conversation['conversation-uri'];
1322 $context_uri = $item['parent-uri'] . '#context';
1324 return $context_uri;
1328 * Returns if the post contains sensitive content ("nsfw")
1330 * @param integer $uri_id
1333 * @throws \Exception
1335 private static function isSensitive($uri_id)
1337 return DBA::exists('tag-view', ['uri-id' => $uri_id, 'name' => 'nsfw']);
1341 * Creates event data
1343 * @param array $item
1345 * @return array with the event data
1346 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1348 public static function createEvent($item)
1351 $event['name'] = $item['event-summary'];
1352 $event['content'] = BBCode::convert($item['event-desc'], false, BBCode::ACTIVITYPUB);
1353 $event['startTime'] = DateTimeFormat::utc($item['event-start'] . '+00:00', DateTimeFormat::ATOM);
1355 if (!$item['event-nofinish']) {
1356 $event['endTime'] = DateTimeFormat::utc($item['event-finish'] . '+00:00', DateTimeFormat::ATOM);
1359 if (!empty($item['event-location'])) {
1360 $item['location'] = $item['event-location'];
1361 $event['location'] = self::createLocation($item);
1368 * Creates a note/article object array
1370 * @param array $item
1372 * @return array with the object data
1373 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1374 * @throws \ImagickException
1376 public static function createNote($item)
1382 if ($item['event-type'] == 'event') {
1384 } elseif (!empty($item['title'])) {
1390 if ($item['deleted']) {
1391 $type = 'Tombstone';
1395 $data['id'] = $item['uri'];
1396 $data['type'] = $type;
1398 if ($item['deleted']) {
1402 $data['summary'] = BBCode::toPlaintext(BBCode::getAbstract($item['body'], Protocol::ACTIVITYPUB));
1404 if ($item['uri'] != $item['thr-parent']) {
1405 $data['inReplyTo'] = $item['thr-parent'];
1407 $data['inReplyTo'] = null;
1410 $data['diaspora:guid'] = $item['guid'];
1411 $data['published'] = DateTimeFormat::utc($item['created'] . '+00:00', DateTimeFormat::ATOM);
1413 if ($item['created'] != $item['edited']) {
1414 $data['updated'] = DateTimeFormat::utc($item['edited'] . '+00:00', DateTimeFormat::ATOM);
1417 $data['url'] = $item['plink'];
1418 $data['attributedTo'] = $item['author-link'];
1419 $data['sensitive'] = self::isSensitive($item['uri-id']);
1420 $data['context'] = self::fetchContextURLForItem($item);
1422 if (!empty($item['title'])) {
1423 $data['name'] = BBCode::toPlaintext($item['title'], false);
1426 $permission_block = self::createPermissionBlockForItem($item, false);
1428 $body = $item['body'];
1430 if ($type == 'Note') {
1431 $body = $item['raw-body'] ?? self::removePictures($body);
1432 } elseif (($type == 'Article') && empty($data['summary'])) {
1433 $data['summary'] = BBCode::toPlaintext(Plaintext::shorten(self::removePictures($body), 1000));
1436 if (empty($item['uid']) || !Feature::isEnabled($item['uid'], 'explicit_mentions')) {
1437 $body = self::prependMentions($body, $item['uri-id'], $item['author-link']);
1440 if ($type == 'Event') {
1441 $data = array_merge($data, self::createEvent($item));
1443 $regexp = "/[@!]\[url\=([^\[\]]*)\].*?\[\/url\]/ism";
1444 $body = preg_replace_callback($regexp, ['self', 'mentionCallback'], $body);
1446 $data['content'] = BBCode::convert($body, false, BBCode::ACTIVITYPUB);
1449 // The regular "content" field does contain a minimized HTML. This is done since systems like
1450 // Mastodon has got problems with - for example - embedded pictures.
1451 // The contentMap does contain the unmodified HTML.
1452 $language = self::getLanguage($item);
1453 if (!empty($language)) {
1454 $regexp = "/[@!]\[url\=([^\[\]]*)\].*?\[\/url\]/ism";
1455 $richbody = preg_replace_callback($regexp, ['self', 'mentionCallback'], $item['body']);
1456 $richbody = BBCode::removeAttachment($richbody);
1458 $data['contentMap'][$language] = BBCode::convert($richbody, false);
1461 $data['source'] = ['content' => $item['body'], 'mediaType' => "text/bbcode"];
1463 if (!empty($item['signed_text']) && ($item['uri'] != $item['thr-parent'])) {
1464 $data['diaspora:comment'] = $item['signed_text'];
1467 $data['attachment'] = self::createAttachmentList($item, $type);
1468 $data['tag'] = self::createTagList($item);
1470 if (empty($data['location']) && (!empty($item['coord']) || !empty($item['location']))) {
1471 $data['location'] = self::createLocation($item);
1474 if (!empty($item['app'])) {
1475 $data['generator'] = ['type' => 'Application', 'name' => $item['app']];
1478 $data = array_merge($data, $permission_block);
1484 * Fetches the language from the post, the user or the system.
1486 * @param array $item
1488 * @return string language string
1490 private static function getLanguage(array $item)
1492 // Try to fetch the language from the post itself
1493 if (!empty($item['language'])) {
1494 $languages = array_keys(json_decode($item['language'], true));
1495 if (!empty($languages[0])) {
1496 return $languages[0];
1500 // Otherwise use the user's language
1501 if (!empty($item['uid'])) {
1502 $user = DBA::selectFirst('user', ['language'], ['uid' => $item['uid']]);
1503 if (!empty($user['language'])) {
1504 return $user['language'];
1508 // And finally just use the system language
1509 return DI::config()->get('system', 'language');
1513 * Creates an an "add tag" entry
1515 * @param array $item
1516 * @param array $data activity data
1518 * @return array with activity data for adding tags
1519 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1520 * @throws \ImagickException
1522 private static function createAddTag($item, $data)
1524 $object = XML::parseString($item['object']);
1525 $target = XML::parseString($item["target"]);
1527 $data['diaspora:guid'] = $item['guid'];
1528 $data['actor'] = $item['author-link'];
1529 $data['target'] = (string)$target->id;
1530 $data['summary'] = BBCode::toPlaintext($item['body']);
1531 $data['object'] = ['id' => (string)$object->id, 'type' => 'tag', 'name' => (string)$object->title, 'content' => (string)$object->content];
1537 * Creates an announce object entry
1539 * @param array $item
1540 * @param array $data activity data
1542 * @return array with activity data
1543 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1544 * @throws \ImagickException
1546 private static function createAnnounce($item, $data)
1548 $orig_body = $item['body'];
1549 $announce = self::getAnnounceArray($item);
1550 if (empty($announce)) {
1551 $data['type'] = 'Create';
1552 $data['object'] = self::createNote($item);
1556 if (empty($announce['comment'])) {
1557 // Pure announce, without a quote
1558 $data['type'] = 'Announce';
1559 $data['object'] = $announce['object']['uri'];
1564 $data['type'] = 'Create';
1565 $item['body'] = $announce['comment'] . "\n" . $announce['object']['plink'];
1566 $data['object'] = self::createNote($item);
1568 /// @todo Finally descide how to implement this in AP. This is a possible way:
1569 $data['object']['attachment'][] = self::createNote($announce['object']);
1571 $data['object']['source']['content'] = $orig_body;
1576 * Return announce related data if the item is an annunce
1578 * @param array $item
1582 public static function getAnnounceArray($item)
1584 $reshared = Item::getShareArray($item);
1585 if (empty($reshared['guid'])) {
1589 $reshared_item = Item::selectFirst([], ['guid' => $reshared['guid']]);
1590 if (!DBA::isResult($reshared_item)) {
1594 if (!in_array($reshared_item['network'], [Protocol::ACTIVITYPUB, Protocol::DFRN])) {
1598 $profile = APContact::getByURL($reshared_item['author-link'], false);
1599 if (empty($profile)) {
1603 return ['object' => $reshared_item, 'actor' => $profile, 'comment' => $reshared['comment']];
1607 * Checks if the provided item array is an announce
1609 * @param array $item
1613 public static function isAnnounce($item)
1615 if (!empty($item['verb']) && ($item['verb'] == Activity::ANNOUNCE)) {
1619 $announce = self::getAnnounceArray($item);
1620 if (empty($announce)) {
1624 return empty($announce['comment']);
1628 * Creates an activity id for a given contact id
1630 * @param integer $cid Contact ID of target
1632 * @return bool|string activity id
1634 public static function activityIDFromContact($cid)
1636 $contact = DBA::selectFirst('contact', ['uid', 'id', 'created'], ['id' => $cid]);
1637 if (!DBA::isResult($contact)) {
1641 $hash = hash('ripemd128', $contact['uid'].'-'.$contact['id'].'-'.$contact['created']);
1642 $uuid = substr($hash, 0, 8). '-' . substr($hash, 8, 4) . '-' . substr($hash, 12, 4) . '-' . substr($hash, 16, 4) . '-' . substr($hash, 20, 12);
1643 return DI::baseUrl() . '/activity/' . $uuid;
1647 * Transmits a contact suggestion to a given inbox
1649 * @param integer $uid User ID
1650 * @param string $inbox Target inbox
1651 * @param integer $suggestion_id Suggestion ID
1653 * @return boolean was the transmission successful?
1654 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1656 public static function sendContactSuggestion($uid, $inbox, $suggestion_id)
1658 $owner = User::getOwnerDataById($uid);
1660 $suggestion = DI::fsuggest()->getById($suggestion_id);
1662 $data = ['@context' => ActivityPub::CONTEXT,
1663 'id' => DI::baseUrl() . '/activity/' . System::createGUID(),
1664 'type' => 'Announce',
1665 'actor' => $owner['url'],
1666 'object' => $suggestion->url,
1667 'content' => $suggestion->note,
1668 'instrument' => self::getService(),
1669 'to' => [ActivityPub::PUBLIC_COLLECTION],
1672 $signed = LDSignature::sign($data, $owner);
1674 Logger::log('Deliver profile deletion for user ' . $uid . ' to ' . $inbox . ' via ActivityPub', Logger::DEBUG);
1675 return HTTPSignature::transmit($signed, $inbox, $uid);
1679 * Transmits a profile relocation to a given inbox
1681 * @param integer $uid User ID
1682 * @param string $inbox Target inbox
1684 * @return boolean was the transmission successful?
1685 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1687 public static function sendProfileRelocation($uid, $inbox)
1689 $owner = User::getOwnerDataById($uid);
1691 $data = ['@context' => ActivityPub::CONTEXT,
1692 'id' => DI::baseUrl() . '/activity/' . System::createGUID(),
1693 'type' => 'dfrn:relocate',
1694 'actor' => $owner['url'],
1695 'object' => $owner['url'],
1696 'published' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
1697 'instrument' => self::getService(),
1698 'to' => [ActivityPub::PUBLIC_COLLECTION],
1701 $signed = LDSignature::sign($data, $owner);
1703 Logger::log('Deliver profile relocation for user ' . $uid . ' to ' . $inbox . ' via ActivityPub', Logger::DEBUG);
1704 return HTTPSignature::transmit($signed, $inbox, $uid);
1708 * Transmits a profile deletion to a given inbox
1710 * @param integer $uid User ID
1711 * @param string $inbox Target inbox
1713 * @return boolean was the transmission successful?
1714 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1716 public static function sendProfileDeletion($uid, $inbox)
1718 $owner = User::getOwnerDataById($uid);
1720 if (empty($owner)) {
1721 Logger::error('No owner data found, the deletion message cannot be processed.', ['user' => $uid]);
1725 if (empty($owner['uprvkey'])) {
1726 Logger::error('No private key for owner found, the deletion message cannot be processed.', ['user' => $uid]);
1730 $data = ['@context' => ActivityPub::CONTEXT,
1731 'id' => DI::baseUrl() . '/activity/' . System::createGUID(),
1733 'actor' => $owner['url'],
1734 'object' => $owner['url'],
1735 'published' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
1736 'instrument' => self::getService(),
1737 'to' => [ActivityPub::PUBLIC_COLLECTION],
1740 $signed = LDSignature::sign($data, $owner);
1742 Logger::log('Deliver profile deletion for user ' . $uid . ' to ' . $inbox . ' via ActivityPub', Logger::DEBUG);
1743 return HTTPSignature::transmit($signed, $inbox, $uid);
1747 * Transmits a profile change to a given inbox
1749 * @param integer $uid User ID
1750 * @param string $inbox Target inbox
1752 * @return boolean was the transmission successful?
1753 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1754 * @throws \ImagickException
1756 public static function sendProfileUpdate($uid, $inbox)
1758 $owner = User::getOwnerDataById($uid);
1759 $profile = APContact::getByURL($owner['url']);
1761 $data = ['@context' => ActivityPub::CONTEXT,
1762 'id' => DI::baseUrl() . '/activity/' . System::createGUID(),
1764 'actor' => $owner['url'],
1765 'object' => self::getProfile($uid),
1766 'published' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
1767 'instrument' => self::getService(),
1768 'to' => [$profile['followers']],
1771 $signed = LDSignature::sign($data, $owner);
1773 Logger::log('Deliver profile update for user ' . $uid . ' to ' . $inbox . ' via ActivityPub', Logger::DEBUG);
1774 return HTTPSignature::transmit($signed, $inbox, $uid);
1778 * Transmits a given activity to a target
1780 * @param string $activity Type name
1781 * @param string $target Target profile
1782 * @param integer $uid User ID
1784 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1785 * @throws \ImagickException
1786 * @throws \Exception
1788 public static function sendActivity($activity, $target, $uid, $id = '')
1790 $profile = APContact::getByURL($target);
1791 if (empty($profile['inbox'])) {
1792 Logger::warning('No inbox found for target', ['target' => $target, 'profile' => $profile]);
1796 $owner = User::getOwnerDataById($uid);
1799 $id = DI::baseUrl() . '/activity/' . System::createGUID();
1802 $data = ['@context' => ActivityPub::CONTEXT,
1804 'type' => $activity,
1805 'actor' => $owner['url'],
1806 'object' => $profile['url'],
1807 'instrument' => self::getService(),
1808 'to' => [$profile['url']]];
1810 Logger::log('Sending activity ' . $activity . ' to ' . $target . ' for user ' . $uid, Logger::DEBUG);
1812 $signed = LDSignature::sign($data, $owner);
1813 return HTTPSignature::transmit($signed, $profile['inbox'], $uid);
1817 * Transmits a "follow object" activity to a target
1818 * This is a preparation for sending automated "follow" requests when receiving "Announce" messages
1820 * @param string $object Object URL
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 sendFollowObject($object, $target, $uid = 0)
1830 $profile = APContact::getByURL($target);
1831 if (empty($profile['inbox'])) {
1832 Logger::warning('No inbox found for target', ['target' => $target, 'profile' => $profile]);
1837 // Fetch the list of administrators
1838 $admin_mail = explode(',', str_replace(' ', '', DI::config()->get('config', 'admin_email')));
1840 // We need to use some user as a sender. It doesn't care who it will send. We will use an administrator account.
1841 $condition = ['verified' => true, 'blocked' => false, 'account_removed' => false, 'account_expired' => false, 'email' => $admin_mail];
1842 $first_user = DBA::selectFirst('user', ['uid'], $condition);
1843 $uid = $first_user['uid'];
1846 $condition = ['verb' => Activity::FOLLOW, 'uid' => 0, 'parent-uri' => $object,
1847 'author-id' => Contact::getPublicIdByUserId($uid)];
1848 if (Item::exists($condition)) {
1849 Logger::log('Follow for ' . $object . ' for user ' . $uid . ' does already exist.', Logger::DEBUG);
1853 $owner = User::getOwnerDataById($uid);
1855 $data = ['@context' => ActivityPub::CONTEXT,
1856 'id' => DI::baseUrl() . '/activity/' . System::createGUID(),
1858 'actor' => $owner['url'],
1859 'object' => $object,
1860 'instrument' => self::getService(),
1861 'to' => [$profile['url']]];
1863 Logger::log('Sending follow ' . $object . ' to ' . $target . ' for user ' . $uid, Logger::DEBUG);
1865 $signed = LDSignature::sign($data, $owner);
1866 return HTTPSignature::transmit($signed, $profile['inbox'], $uid);
1870 * Transmit a message that the contact request had been accepted
1872 * @param string $target Target profile
1874 * @param integer $uid User ID
1875 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1876 * @throws \ImagickException
1878 public static function sendContactAccept($target, $id, $uid)
1880 $profile = APContact::getByURL($target);
1881 if (empty($profile['inbox'])) {
1882 Logger::warning('No inbox found for target', ['target' => $target, 'profile' => $profile]);
1886 $owner = User::getOwnerDataById($uid);
1887 $data = ['@context' => ActivityPub::CONTEXT,
1888 'id' => DI::baseUrl() . '/activity/' . System::createGUID(),
1890 'actor' => $owner['url'],
1892 'id' => (string)$id,
1894 'actor' => $profile['url'],
1895 'object' => $owner['url']
1897 'instrument' => self::getService(),
1898 'to' => [$profile['url']]];
1900 Logger::debug('Sending accept to ' . $target . ' for user ' . $uid . ' with id ' . $id);
1902 $signed = LDSignature::sign($data, $owner);
1903 HTTPSignature::transmit($signed, $profile['inbox'], $uid);
1907 * Reject a contact request or terminates the contact relation
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 sendContactReject($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 reject to ' . $target . ' for user ' . $uid . ' with id ' . $id);
1939 $signed = LDSignature::sign($data, $owner);
1940 HTTPSignature::transmit($signed, $profile['inbox'], $uid);
1944 * Transmits a message that we don't want to follow this contact anymore
1946 * @param string $target Target profile
1947 * @param integer $uid User ID
1948 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1949 * @throws \ImagickException
1950 * @throws \Exception
1951 * @return bool success
1953 public static function sendContactUndo($target, $cid, $uid)
1955 $profile = APContact::getByURL($target);
1956 if (empty($profile['inbox'])) {
1957 Logger::warning('No inbox found for target', ['target' => $target, 'profile' => $profile]);
1961 $object_id = self::activityIDFromContact($cid);
1962 if (empty($object_id)) {
1966 $id = DI::baseUrl() . '/activity/' . System::createGUID();
1968 $owner = User::getOwnerDataById($uid);
1969 $data = ['@context' => ActivityPub::CONTEXT,
1972 'actor' => $owner['url'],
1973 'object' => ['id' => $object_id, 'type' => 'Follow',
1974 'actor' => $owner['url'],
1975 'object' => $profile['url']],
1976 'instrument' => self::getService(),
1977 'to' => [$profile['url']]];
1979 Logger::log('Sending undo to ' . $target . ' for user ' . $uid . ' with id ' . $id, Logger::DEBUG);
1981 $signed = LDSignature::sign($data, $owner);
1982 return HTTPSignature::transmit($signed, $profile['inbox'], $uid);
1985 private static function prependMentions($body, int $uriid, string $authorLink)
1989 foreach (Tag::getByURIId($uriid, [Tag::IMPLICIT_MENTION]) as $tag) {
1990 $profile = Contact::getByURL($tag['url'], false, ['addr', 'contact-type', 'nick']);
1991 if (!empty($profile['addr'])
1992 && $profile['contact-type'] != Contact::TYPE_COMMUNITY
1993 && !strstr($body, $profile['addr'])
1994 && !strstr($body, $tag['url'])
1995 && $tag['url'] !== $authorLink
1997 $mentions[] = '@[url=' . $tag['url'] . ']' . $profile['nick'] . '[/url]';
2001 $mentions[] = $body;
2003 return implode(' ', $mentions);