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_id = Contact::getIdForURL($url);
96 $activity_id = ActivityPub\Transmitter::activityIDFromContact($contact_id);
97 $success = ActivityPub\Transmitter::sendActivity('Follow', $url, 0, $activity_id);
99 DBA::update('contact', ['rel' => Contact::FRIEND], ['id' => $contact_id]);
106 * Unsubscribe from a relay
108 * @param string $url Subscribe actor url
109 * @return bool success
111 public static function sendRelayUndoFollow(string $url)
113 $contact_id = Contact::getIdForURL($url);
118 $success = self::sendContactUndo($url, $contact_id, 0);
120 DBA::update('contact', ['rel' => Contact::SHARING], ['id' => $contact_id]);
127 * Collects a list of contacts of the given owner
129 * @param array $owner Owner array
130 * @param int|array $rel The relevant value(s) contact.rel should match
131 * @param string $module The name of the relevant AP endpoint module (followers|following)
132 * @param integer $page Page number
134 * @return array of owners
137 public static function getContacts($owner, $rel, $module, $page = null)
141 'uid' => $owner['uid'],
148 $condition = DBA::buildCondition($parameters);
150 $sql = "SELECT COUNT(*) as `count`
152 JOIN `apcontact` ON `apcontact`.`url` = `contact`.`url`
155 $contacts = DBA::fetchFirst($sql, ...$parameters);
157 $modulePath = '/' . $module . '/';
159 $data = ['@context' => ActivityPub::CONTEXT];
160 $data['id'] = DI::baseUrl() . $modulePath . $owner['nickname'];
161 $data['type'] = 'OrderedCollection';
162 $data['totalItems'] = $contacts['count'];
164 // When we hide our friends we will only show the pure number but don't allow more.
165 $profile = Profile::getByUID($owner['uid']);
166 if (!empty($profile['hide-friends'])) {
171 $data['first'] = DI::baseUrl() . $modulePath . $owner['nickname'] . '?page=1';
173 $data['type'] = 'OrderedCollectionPage';
176 $sql = "SELECT `contact`.`url`
178 JOIN `apcontact` ON `apcontact`.`url` = `contact`.`url`
182 $parameters[] = ($page - 1) * 100;
185 $contacts = DBA::p($sql, ...$parameters);
186 while ($contact = DBA::fetch($contacts)) {
187 $list[] = $contact['url'];
189 DBA::close($contacts);
192 $data['next'] = DI::baseUrl() . $modulePath . $owner['nickname'] . '?page=' . ($page + 1);
195 $data['partOf'] = DI::baseUrl() . $modulePath . $owner['nickname'];
197 $data['orderedItems'] = $list;
204 * Public posts for the given owner
206 * @param array $owner Owner array
207 * @param integer $page Page number
208 * @param string $requester URL of requesting account
210 * @return array of posts
211 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
212 * @throws \ImagickException
214 public static function getOutbox($owner, $page = null, $requester = '')
216 $public_contact = Contact::getIdForURL($owner['url']);
217 $condition = ['uid' => 0, 'contact-id' => $public_contact,
218 'private' => [Item::PUBLIC, Item::UNLISTED]];
220 if (!empty($requester)) {
221 $requester_id = Contact::getIdForURL($requester, $owner['uid']);
222 if (!empty($requester_id)) {
223 $permissionSets = DI::permissionSet()->selectByContactId($requester_id, $owner['uid']);
224 if (!empty($permissionSets)) {
225 $condition = ['uid' => $owner['uid'], 'origin' => true,
226 'psid' => array_merge($permissionSets->column('id'),
227 [DI::permissionSet()->getIdFromACL($owner['uid'], '', '', '', '')])];
232 $condition = array_merge($condition,
233 ['author-id' => $public_contact,
234 'gravity' => [GRAVITY_PARENT, GRAVITY_COMMENT],
235 'deleted' => false, 'visible' => true, 'moderated' => false]);
237 $count = DBA::count('item', $condition);
239 $data = ['@context' => ActivityPub::CONTEXT];
240 $data['id'] = DI::baseUrl() . '/outbox/' . $owner['nickname'];
241 $data['type'] = 'OrderedCollection';
242 $data['totalItems'] = $count;
245 $data['first'] = DI::baseUrl() . '/outbox/' . $owner['nickname'] . '?page=1';
247 $data['type'] = 'OrderedCollectionPage';
250 $condition['parent-network'] = Protocol::NATIVE_SUPPORT;
252 $items = Item::select(['id'], $condition, ['limit' => [($page - 1) * 20, 20], 'order' => ['created' => true]]);
253 while ($item = Item::fetch($items)) {
254 $activity = self::createActivityFromItem($item['id'], true);
255 $activity['type'] = $activity['type'] == 'Update' ? 'Create' : $activity['type'];
257 // Only list "Create" activity objects here, no reshares
258 if (!empty($activity['object']) && ($activity['type'] == 'Create')) {
259 $list[] = $activity['object'];
264 $data['next'] = DI::baseUrl() . '/outbox/' . $owner['nickname'] . '?page=' . ($page + 1);
267 $data['partOf'] = DI::baseUrl() . '/outbox/' . $owner['nickname'];
269 $data['orderedItems'] = $list;
276 * Return the service array containing information the used software and it's url
278 * @return array with service data
280 private static function getService()
282 return ['type' => 'Service',
283 'name' => FRIENDICA_PLATFORM . " '" . FRIENDICA_CODENAME . "' " . FRIENDICA_VERSION . '-' . DB_UPDATE_VERSION,
284 'url' => DI::baseUrl()->get()];
288 * Return the ActivityPub profile of the given user
290 * @param integer $uid User ID
291 * @return array with profile data
292 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
294 public static function getProfile($uid)
297 $condition = ['uid' => $uid, 'blocked' => false, 'account_expired' => false,
298 'account_removed' => false, 'verified' => true];
299 $fields = ['guid', 'nickname', 'pubkey', 'account-type', 'page-flags'];
300 $user = DBA::selectFirst('user', $fields, $condition);
301 if (!DBA::isResult($user)) {
305 $fields = ['locality', 'region', 'country-name'];
306 $profile = DBA::selectFirst('profile', $fields, ['uid' => $uid]);
307 if (!DBA::isResult($profile)) {
311 $fields = ['name', 'url', 'location', 'about', 'avatar', 'photo'];
312 $contact = DBA::selectFirst('contact', $fields, ['uid' => $uid, 'self' => true]);
313 if (!DBA::isResult($contact)) {
317 $contact = User::getSystemAccount();
318 $user = ['guid' => '', 'nickname' => $contact['nick'], 'pubkey' => $contact['pubkey'],
319 'account-type' => $contact['contact-type'], 'page-flags' => User::PAGE_FLAGS_NORMAL];
320 $profile = ['locality' => '', 'region' => '', 'country-name' => ''];
323 $data = ['@context' => ActivityPub::CONTEXT];
324 $data['id'] = $contact['url'];
326 if (!empty($user['guid'])) {
327 $data['diaspora:guid'] = $user['guid'];
330 $data['type'] = ActivityPub::ACCOUNT_TYPES[$user['account-type']];
333 $data['following'] = DI::baseUrl() . '/following/' . $user['nickname'];
334 $data['followers'] = DI::baseUrl() . '/followers/' . $user['nickname'];
335 $data['inbox'] = DI::baseUrl() . '/inbox/' . $user['nickname'];
336 $data['outbox'] = DI::baseUrl() . '/outbox/' . $user['nickname'];
338 $data['inbox'] = DI::baseUrl() . '/friendica/inbox';
341 $data['preferredUsername'] = $user['nickname'];
342 $data['name'] = $contact['name'];
344 if (!empty($profile['country-name'] . $profile['region'] . $profile['locality'])) {
345 $data['vcard:hasAddress'] = ['@type' => 'vcard:Home', 'vcard:country-name' => $profile['country-name'],
346 'vcard:region' => $profile['region'], 'vcard:locality' => $profile['locality']];
349 if (!empty($contact['about'])) {
350 $data['summary'] = BBCode::convert($contact['about'], false);
353 $data['url'] = $contact['url'];
354 $data['manuallyApprovesFollowers'] = in_array($user['page-flags'], [User::PAGE_FLAGS_NORMAL, User::PAGE_FLAGS_PRVGROUP]);
355 $data['publicKey'] = ['id' => $contact['url'] . '#main-key',
356 'owner' => $contact['url'],
357 'publicKeyPem' => $user['pubkey']];
358 $data['endpoints'] = ['sharedInbox' => DI::baseUrl() . '/inbox'];
359 $data['icon'] = ['type' => 'Image',
360 'url' => $contact['photo']];
362 $data['generator'] = self::getService();
364 // tags: https://kitty.town/@inmysocks/100656097926961126.json
369 * @param string $username
371 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
373 public static function getDeletedUser($username)
376 '@context' => ActivityPub::CONTEXT,
377 'id' => DI::baseUrl() . '/profile/' . $username,
378 'type' => 'Tombstone',
379 'published' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
380 'updated' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
381 'deleted' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
386 * Returns an array with permissions of a given item array
390 * @return array with permissions
391 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
392 * @throws \ImagickException
394 private static function fetchPermissionBlockFromConversation($item)
396 if (empty($item['thr-parent'])) {
400 $condition = ['item-uri' => $item['thr-parent'], 'protocol' => Conversation::PARCEL_ACTIVITYPUB];
401 $conversation = DBA::selectFirst('conversation', ['source'], $condition);
402 if (!DBA::isResult($conversation)) {
406 $activity = json_decode($conversation['source'], true);
408 $actor = JsonLD::fetchElement($activity, 'actor', 'id');
409 $profile = APContact::getByURL($actor);
411 $item_profile = APContact::getByURL($item['author-link']);
412 $exclude[] = $item['author-link'];
414 if ($item['gravity'] == GRAVITY_PARENT) {
415 $exclude[] = $item['owner-link'];
418 $permissions['to'][] = $actor;
420 foreach (['to', 'cc', 'bto', 'bcc'] as $element) {
421 if (empty($activity[$element])) {
424 if (is_string($activity[$element])) {
425 $activity[$element] = [$activity[$element]];
428 foreach ($activity[$element] as $receiver) {
429 if (empty($receiver)) {
433 if (!empty($profile['followers']) && $receiver == $profile['followers'] && !empty($item_profile['followers'])) {
434 $permissions[$element][] = $item_profile['followers'];
435 } elseif (!in_array($receiver, $exclude)) {
436 $permissions[$element][] = $receiver;
444 * Creates an array of permissions from an item thread
446 * @param array $item Item array
447 * @param boolean $blindcopy addressing via "bcc" or "cc"?
448 * @param integer $last_id Last item id for adding receivers
449 * @param boolean $forum_mode "true" means that we are sending content to a forum
451 * @return array with permission data
452 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
453 * @throws \ImagickException
455 private static function createPermissionBlockForItem($item, $blindcopy, $last_id = 0, $forum_mode = false)
458 $last_id = $item['id'];
464 // Check if we should always deliver our stuff via BCC
465 if (!empty($item['uid'])) {
466 $profile = User::getOwnerDataById($item['uid']);
467 if (!empty($profile)) {
468 $always_bcc = $profile['hide-friends'];
469 $isforum = $profile['account-type'] == User::ACCOUNT_TYPE_COMMUNITY;
473 if (DI::config()->get('system', 'ap_always_bcc')) {
477 if ((self::isAnnounce($item) && !$isforum) || DI::config()->get('debug', 'total_ap_delivery')) {
478 // Will be activated in a later step
479 $networks = Protocol::FEDERATED;
481 // For now only send to these contacts:
482 $networks = [Protocol::ACTIVITYPUB, Protocol::OSTATUS];
485 $data = ['to' => [], 'cc' => [], 'bcc' => []];
487 if ($item['gravity'] == GRAVITY_PARENT) {
488 $actor_profile = APContact::getByURL($item['owner-link']);
490 $actor_profile = APContact::getByURL($item['author-link']);
493 $terms = Tag::getByURIId($item['uri-id'], [Tag::MENTION, Tag::IMPLICIT_MENTION, Tag::EXCLUSIVE_MENTION]);
495 if ($item['private'] != Item::PRIVATE) {
496 // Directly mention the original author upon a quoted reshare.
497 // Else just ensure that the original author receives the reshare.
498 $announce = self::getAnnounceArray($item);
499 if (!empty($announce['comment'])) {
500 $data['to'][] = $announce['actor']['url'];
501 } elseif (!empty($announce)) {
502 $data['cc'][] = $announce['actor']['url'];
505 $data = array_merge($data, self::fetchPermissionBlockFromConversation($item));
507 // Check if the item is completely public or unlisted
508 if ($item['private'] == Item::PUBLIC) {
509 $data['to'][] = ActivityPub::PUBLIC_COLLECTION;
511 $data['cc'][] = ActivityPub::PUBLIC_COLLECTION;
514 foreach ($terms as $term) {
515 $profile = APContact::getByURL($term['url'], false);
516 if (!empty($profile)) {
517 $data['to'][] = $profile['url'];
521 $receiver_list = Item::enumeratePermissions($item, true);
523 foreach ($terms as $term) {
524 $cid = Contact::getIdForURL($term['url'], $item['uid']);
525 if (!empty($cid) && in_array($cid, $receiver_list)) {
526 $contact = DBA::selectFirst('contact', ['url', 'network', 'protocol'], ['id' => $cid]);
527 if (!DBA::isResult($contact) || (!in_array($contact['network'], $networks) && ($contact['protocol'] != Protocol::ACTIVITYPUB))) {
531 if ($isforum && DBA::isResult($contact) && ($contact['dfrn'] == Protocol::DFRN)) {
535 if (!empty($profile = APContact::getByURL($contact['url'], false))) {
536 $data['to'][] = $profile['url'];
541 foreach ($receiver_list as $receiver) {
542 $contact = DBA::selectFirst('contact', ['url', 'hidden', 'network', 'protocol'], ['id' => $receiver]);
543 if (!DBA::isResult($contact) || (!in_array($contact['network'], $networks) && ($contact['protocol'] != Protocol::ACTIVITYPUB))) {
547 if ($isforum && DBA::isResult($contact) && ($contact['dfrn'] == Protocol::DFRN)) {
551 if (!empty($profile = APContact::getByURL($contact['url'], false))) {
552 if ($contact['hidden'] || $always_bcc) {
553 $data['bcc'][] = $profile['url'];
555 $data['cc'][] = $profile['url'];
561 if (!empty($item['parent'])) {
562 $parents = Item::select(['id', 'author-link', 'owner-link', 'gravity', 'uri'], ['parent' => $item['parent']]);
563 while ($parent = Item::fetch($parents)) {
564 if ($parent['gravity'] == GRAVITY_PARENT) {
565 $profile = APContact::getByURL($parent['owner-link'], false);
566 if (!empty($profile)) {
567 if ($item['gravity'] != GRAVITY_PARENT) {
568 // Comments to forums are directed to the forum
569 // But comments to forums aren't directed to the followers collection
570 // This rule is only valid when the actor isn't the forum.
571 // The forum needs to transmit their content to their followers.
572 if (($profile['type'] == 'Group') && ($profile['url'] != $actor_profile['url'])) {
573 $data['to'][] = $profile['url'];
575 $data['cc'][] = $profile['url'];
576 if (($item['private'] != Item::PRIVATE) && !empty($actor_profile['followers'])) {
577 $data['cc'][] = $actor_profile['followers'];
581 // Public thread parent post always are directed to the followers
582 if (($item['private'] != Item::PRIVATE) && !$forum_mode) {
583 $data['cc'][] = $actor_profile['followers'];
589 // Don't include data from future posts
590 if ($parent['id'] >= $last_id) {
594 $profile = APContact::getByURL($parent['author-link'], false);
595 if (!empty($profile)) {
596 if (($profile['type'] == 'Group') || ($parent['uri'] == $item['thr-parent'])) {
597 $data['to'][] = $profile['url'];
599 $data['cc'][] = $profile['url'];
603 DBA::close($parents);
606 $data['to'] = array_unique($data['to']);
607 $data['cc'] = array_unique($data['cc']);
608 $data['bcc'] = array_unique($data['bcc']);
610 if (($key = array_search($item['author-link'], $data['to'])) !== false) {
611 unset($data['to'][$key]);
614 if (($key = array_search($item['author-link'], $data['cc'])) !== false) {
615 unset($data['cc'][$key]);
618 if (($key = array_search($item['author-link'], $data['bcc'])) !== false) {
619 unset($data['bcc'][$key]);
622 foreach ($data['to'] as $to) {
623 if (($key = array_search($to, $data['cc'])) !== false) {
624 unset($data['cc'][$key]);
627 if (($key = array_search($to, $data['bcc'])) !== false) {
628 unset($data['bcc'][$key]);
632 foreach ($data['cc'] as $cc) {
633 if (($key = array_search($cc, $data['bcc'])) !== false) {
634 unset($data['bcc'][$key]);
638 $receivers = ['to' => array_values($data['to']), 'cc' => array_values($data['cc']), 'bcc' => array_values($data['bcc'])];
641 unset($receivers['bcc']);
648 * Check if an inbox is archived
650 * @param string $url Inbox url
652 * @return boolean "true" if inbox is archived
654 private static function archivedInbox($url)
656 return DBA::exists('inbox-status', ['url' => $url, 'archive' => true]);
660 * Fetches a list of inboxes of followers of a given user
662 * @param integer $uid User ID
663 * @param boolean $personal fetch personal inboxes
665 * @return array of follower inboxes
666 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
667 * @throws \ImagickException
669 public static function fetchTargetInboxesforUser($uid, $personal = false)
675 if (!empty($item['uid'])) {
676 $profile = User::getOwnerDataById($item['uid']);
677 if (!empty($profile)) {
678 $isforum = $profile['account-type'] == User::ACCOUNT_TYPE_COMMUNITY;
682 if (DI::config()->get('debug', 'total_ap_delivery')) {
683 // Will be activated in a later step
684 $networks = Protocol::FEDERATED;
686 // For now only send to these contacts:
687 $networks = [Protocol::ACTIVITYPUB, Protocol::OSTATUS];
690 $condition = ['uid' => $uid, 'archive' => false, 'pending' => false];
693 $condition['rel'] = [Contact::FOLLOWER, Contact::FRIEND];
696 $contacts = DBA::select('contact', ['url', 'network', 'protocol'], $condition);
697 while ($contact = DBA::fetch($contacts)) {
698 if (Contact::isLocal($contact['url'])) {
702 if (!in_array($contact['network'], $networks) && ($contact['protocol'] != Protocol::ACTIVITYPUB)) {
706 if ($isforum && ($contact['dfrn'] == Protocol::DFRN)) {
710 if (Network::isUrlBlocked($contact['url'])) {
714 $profile = APContact::getByURL($contact['url'], false);
715 if (!empty($profile)) {
716 if (empty($profile['sharedinbox']) || $personal) {
717 $target = $profile['inbox'];
719 $target = $profile['sharedinbox'];
721 if (!self::archivedInbox($target)) {
722 $inboxes[$target] = $target;
726 DBA::close($contacts);
732 * Fetches an array of inboxes for the given item and user
734 * @param array $item Item array
735 * @param integer $uid User ID
736 * @param boolean $personal fetch personal inboxes
737 * @param integer $last_id Last item id for adding receivers
738 * @param boolean $forum_mode "true" means that we are sending content to a forum
739 * @return array with inboxes
740 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
741 * @throws \ImagickException
743 public static function fetchTargetInboxes($item, $uid, $personal = false, $last_id = 0, $forum_mode = false)
745 $permissions = self::createPermissionBlockForItem($item, true, $last_id, $forum_mode);
746 if (empty($permissions)) {
752 if ($item['gravity'] == GRAVITY_ACTIVITY) {
753 $item_profile = APContact::getByURL($item['author-link'], false);
755 $item_profile = APContact::getByURL($item['owner-link'], false);
758 if (empty($item_profile)) {
762 $profile_uid = User::getIdForURL($item_profile['url']);
764 foreach (['to', 'cc', 'bto', 'bcc'] as $element) {
765 if (empty($permissions[$element])) {
769 $blindcopy = in_array($element, ['bto', 'bcc']);
771 foreach ($permissions[$element] as $receiver) {
772 if (empty($receiver) || Network::isUrlBlocked($receiver)) {
776 if ($item_profile && ($receiver == $item_profile['followers']) && ($uid == $profile_uid)) {
777 $inboxes = array_merge($inboxes, self::fetchTargetInboxesforUser($uid, $personal));
779 if (Contact::isLocal($receiver)) {
783 $profile = APContact::getByURL($receiver, false);
784 if (!empty($profile)) {
785 if (empty($profile['sharedinbox']) || $personal || $blindcopy) {
786 $target = $profile['inbox'];
788 $target = $profile['sharedinbox'];
790 if (!self::archivedInbox($target)) {
791 $inboxes[$target] = $target;
802 * Creates an array in the structure of the item table for a given mail id
804 * @param integer $mail_id
809 public static function ItemArrayFromMail($mail_id)
811 $mail = DBA::selectFirst('mail', [], ['id' => $mail_id]);
812 if (!DBA::isResult($mail)) {
816 $mail['uri-id'] = ItemURI::insert(['uri' => $mail['uri'], 'guid' => $mail['guid']]);
818 $reply = DBA::selectFirst('mail', ['uri'], ['parent-uri' => $mail['parent-uri'], 'reply' => false]);
820 // Making the post more compatible for Mastodon by:
821 // - Making it a note and not an article (no title)
822 // - Moving the title into the "summary" field that is used as a "content warning"
823 $mail['body'] = '[abstract]' . $mail['title'] . "[/abstract]\n" . $mail['body'];
826 $mail['author-link'] = $mail['owner-link'] = $mail['from-url'];
827 $mail['allow_cid'] = '<'.$mail['contact-id'].'>';
828 $mail['allow_gid'] = '';
829 $mail['deny_cid'] = '';
830 $mail['deny_gid'] = '';
831 $mail['private'] = true;
832 $mail['deleted'] = false;
833 $mail['edited'] = $mail['created'];
834 $mail['plink'] = $mail['uri'];
835 $mail['thr-parent'] = $reply['uri'];
836 $mail['gravity'] = ($mail['reply'] ? GRAVITY_COMMENT: GRAVITY_PARENT);
838 $mail['event-type'] = '';
839 $mail['attach'] = '';
847 * Creates an activity array for a given mail id
849 * @param integer $mail_id
850 * @param boolean $object_mode Is the activity item is used inside another object?
852 * @return array of activity
855 public static function createActivityFromMail($mail_id, $object_mode = false)
857 $mail = self::ItemArrayFromMail($mail_id);
861 $object = self::createNote($mail);
864 $data = ['@context' => ActivityPub::CONTEXT];
869 $data['id'] = $mail['uri'] . '/Create';
870 $data['type'] = 'Create';
871 $data['actor'] = $mail['author-link'];
872 $data['published'] = DateTimeFormat::utc($mail['created'] . '+00:00', DateTimeFormat::ATOM);
873 $data['instrument'] = self::getService();
874 $data = array_merge($data, self::createPermissionBlockForItem($mail, true));
876 if (empty($data['to']) && !empty($data['cc'])) {
877 $data['to'] = $data['cc'];
880 if (empty($data['to']) && !empty($data['bcc'])) {
881 $data['to'] = $data['bcc'];
887 $object['to'] = $data['to'];
888 $object['tag'] = [['type' => 'Mention', 'href' => $object['to'][0], 'name' => '']];
890 unset($object['cc']);
891 unset($object['bcc']);
893 $data['directMessage'] = true;
895 $data['object'] = $object;
897 $owner = User::getOwnerDataById($mail['uid']);
899 if (!$object_mode && !empty($owner)) {
900 return LDSignature::sign($data, $owner);
907 * Returns the activity type of a given item
911 * @return string with activity type
912 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
913 * @throws \ImagickException
915 private static function getTypeOfItem($item)
919 // Only check for a reshare, if it is a real reshare and no quoted reshare
920 if (strpos($item['body'], "[share") === 0) {
921 $announce = self::getAnnounceArray($item);
922 $reshared = !empty($announce);
927 } elseif ($item['verb'] == Activity::POST) {
928 if ($item['created'] == $item['edited']) {
933 } elseif ($item['verb'] == Activity::LIKE) {
935 } elseif ($item['verb'] == Activity::DISLIKE) {
937 } elseif ($item['verb'] == Activity::ATTEND) {
939 } elseif ($item['verb'] == Activity::ATTENDNO) {
941 } elseif ($item['verb'] == Activity::ATTENDMAYBE) {
942 $type = 'TentativeAccept';
943 } elseif ($item['verb'] == Activity::FOLLOW) {
945 } elseif ($item['verb'] == Activity::TAG) {
947 } elseif ($item['verb'] == Activity::ANNOUNCE) {
957 * Creates the activity or fetches it from the cache
959 * @param integer $item_id
960 * @param boolean $force Force new cache entry
962 * @return array with the activity
965 public static function createCachedActivityFromItem($item_id, $force = false)
967 $cachekey = 'APDelivery:createActivity:' . $item_id;
970 $data = DI::cache()->get($cachekey);
971 if (!is_null($data)) {
976 $data = self::createActivityFromItem($item_id);
978 DI::cache()->set($cachekey, $data, Duration::QUARTER_HOUR);
983 * Creates an activity array for a given item id
985 * @param integer $item_id
986 * @param boolean $object_mode Is the activity item is used inside another object?
988 * @return array of activity
991 public static function createActivityFromItem($item_id, $object_mode = false)
993 Logger::info('Fetching activity', ['item' => $item_id]);
994 $item = Item::selectFirst([], ['id' => $item_id, 'parent-network' => Protocol::NATIVE_SUPPORT]);
995 if (!DBA::isResult($item)) {
999 // In case of a forum post ensure to return the original post if author and forum are on the same machine
1000 if (!empty($item['forum_mode'])) {
1001 $author = Contact::getById($item['author-id'], ['nurl']);
1002 if (!empty($author['nurl'])) {
1003 $self = Contact::selectFirst(['uid'], ['nurl' => $author['nurl'], 'self' => true]);
1004 if (!empty($self['uid'])) {
1005 $item = Item::selectFirst([], ['uri-id' => $item['uri-id'], 'uid' => $self['uid']]);
1011 $condition = ['item-uri' => $item['uri'], 'protocol' => Conversation::PARCEL_ACTIVITYPUB];
1012 $conversation = DBA::selectFirst('conversation', ['source'], $condition);
1013 if (DBA::isResult($conversation)) {
1014 $data = json_decode($conversation['source'], true);
1015 if (!empty($data['type'])) {
1016 if (in_array($data['type'], ['Create', 'Update'])) {
1018 unset($data['@context']);
1019 unset($data['signature']);
1021 Logger::info('Return stored conversation', ['item' => $item_id]);
1023 } elseif (in_array('as:' . $data['type'], Receiver::CONTENT_TYPES)) {
1024 if (!empty($data['@context'])) {
1025 $context = $data['@context'];
1026 unset($data['@context']);
1028 unset($data['actor']);
1034 $type = self::getTypeOfItem($item);
1037 if (!$object_mode) {
1038 $data = ['@context' => $context ?? ActivityPub::CONTEXT];
1040 if ($item['deleted'] && ($item['gravity'] == GRAVITY_ACTIVITY)) {
1042 } elseif ($item['deleted']) {
1049 if (($item['gravity'] == GRAVITY_ACTIVITY) && ($type != 'Undo')) {
1050 $data['id'] = $item['uri'];
1052 $data['id'] = $item['uri'] . '/' . $type;
1055 $data['type'] = $type;
1057 if (($type != 'Announce') || ($item['gravity'] != GRAVITY_PARENT)) {
1058 $data['actor'] = $item['author-link'];
1060 $data['actor'] = $item['owner-link'];
1063 $data['published'] = DateTimeFormat::utc($item['created'] . '+00:00', DateTimeFormat::ATOM);
1065 $data['instrument'] = self::getService();
1067 $data = array_merge($data, self::createPermissionBlockForItem($item, false));
1069 if (in_array($data['type'], ['Create', 'Update', 'Delete'])) {
1070 $data['object'] = $object ?? self::createNote($item);
1071 } elseif ($data['type'] == 'Add') {
1072 $data = self::createAddTag($item, $data);
1073 } elseif ($data['type'] == 'Announce') {
1074 if ($item['verb'] == ACTIVITY::ANNOUNCE) {
1075 $data['object'] = $item['thr-parent'];
1077 $data = self::createAnnounce($item, $data);
1079 } elseif ($data['type'] == 'Follow') {
1080 $data['object'] = $item['parent-uri'];
1081 } elseif ($data['type'] == 'Undo') {
1082 $data['object'] = self::createActivityFromItem($item_id, true);
1084 $data['diaspora:guid'] = $item['guid'];
1085 if (!empty($item['signed_text'])) {
1086 $data['diaspora:like'] = $item['signed_text'];
1088 $data['object'] = $item['thr-parent'];
1091 if (!empty($item['contact-uid'])) {
1092 $uid = $item['contact-uid'];
1094 $uid = $item['uid'];
1097 $owner = User::getOwnerDataById($uid);
1099 Logger::info('Fetched activity', ['item' => $item_id, 'uid' => $uid]);
1101 // We don't sign if we aren't the actor. This is important for relaying content especially for forums
1102 if (!$object_mode && !empty($owner) && ($data['actor'] == $owner['url'])) {
1103 return LDSignature::sign($data, $owner);
1108 /// @todo Create "conversation" entry
1112 * Creates a location entry for a given item array
1114 * @param array $item
1116 * @return array with location array
1118 private static function createLocation($item)
1120 $location = ['type' => 'Place'];
1122 if (!empty($item['location'])) {
1123 $location['name'] = $item['location'];
1128 if (empty($item['coord'])) {
1129 $coord = Map::getCoordinates($item['location']);
1131 $coords = explode(' ', $item['coord']);
1132 if (count($coords) == 2) {
1133 $coord = ['lat' => $coords[0], 'lon' => $coords[1]];
1137 if (!empty($coord['lat']) && !empty($coord['lon'])) {
1138 $location['latitude'] = $coord['lat'];
1139 $location['longitude'] = $coord['lon'];
1146 * Returns a tag array for a given item array
1148 * @param array $item
1150 * @return array of tags
1151 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1153 private static function createTagList($item)
1157 $terms = Tag::getByURIId($item['uri-id'], [Tag::HASHTAG, Tag::MENTION, Tag::IMPLICIT_MENTION, Tag::EXCLUSIVE_MENTION]);
1158 foreach ($terms as $term) {
1159 if ($term['type'] == Tag::HASHTAG) {
1160 $url = DI::baseUrl() . '/search?tag=' . urlencode($term['name']);
1161 $tags[] = ['type' => 'Hashtag', 'href' => $url, 'name' => '#' . $term['name']];
1163 $contact = Contact::getByURL($term['url'], false, ['addr']);
1164 if (empty($contact)) {
1167 if (!empty($contact['addr'])) {
1168 $mention = '@' . $contact['addr'];
1170 $mention = '@' . $term['url'];
1173 $tags[] = ['type' => 'Mention', 'href' => $term['url'], 'name' => $mention];
1177 $announce = self::getAnnounceArray($item);
1178 // Mention the original author upon commented reshares
1179 if (!empty($announce['comment'])) {
1180 $tags[] = ['type' => 'Mention', 'href' => $announce['actor']['url'], 'name' => '@' . $announce['actor']['addr']];
1187 * Adds attachment data to the JSON document
1189 * @param array $item Data of the item that is to be posted
1190 * @param string $type Object type
1192 * @return array with attachment data
1193 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1195 private static function createAttachmentList($item, $type)
1199 // Currently deactivated, since it creates side effects on Mastodon and Pleroma.
1200 // It will be reactivated, once this cleared.
1202 $attach_data = BBCode::getAttachmentData($item['body']);
1203 if (!empty($attach_data['url'])) {
1204 $attachment = ['type' => 'Page',
1205 'mediaType' => 'text/html',
1206 'url' => $attach_data['url']];
1208 if (!empty($attach_data['title'])) {
1209 $attachment['name'] = $attach_data['title'];
1212 if (!empty($attach_data['description'])) {
1213 $attachment['summary'] = $attach_data['description'];
1216 if (!empty($attach_data['image'])) {
1217 $imgdata = Images::getInfoFromURLCached($attach_data['image']);
1219 $attachment['icon'] = ['type' => 'Image',
1220 'mediaType' => $imgdata['mime'],
1221 'width' => $imgdata[0],
1222 'height' => $imgdata[1],
1223 'url' => $attach_data['image']];
1227 $attachments[] = $attachment;
1230 $arr = explode('[/attach],', $item['attach']);
1232 foreach ($arr as $r) {
1234 $cnt = preg_match('|\[attach\]href=\"(.*?)\" length=\"(.*?)\" type=\"(.*?)\" title=\"(.*?)\"|', $r, $matches);
1236 $attributes = ['type' => 'Document',
1237 'mediaType' => $matches[3],
1238 'url' => $matches[1],
1241 if (trim($matches[4]) != '') {
1242 $attributes['name'] = trim($matches[4]);
1245 $attachments[] = $attributes;
1250 if ($type != 'Note') {
1251 return $attachments;
1254 // Simplify image codes
1255 $body = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '[img]$3[/img]', $item['body']);
1257 // Grab all pictures without alternative descriptions and create attachments out of them
1258 if (preg_match_all("/\[img\]([^\[\]]*)\[\/img\]/Usi", $body, $pictures)) {
1259 foreach ($pictures[1] as $picture) {
1260 $imgdata = Images::getInfoFromURLCached($picture);
1262 $attachments[] = ['type' => 'Document',
1263 'mediaType' => $imgdata['mime'],
1270 // Grab all pictures with alternative description and create attachments out of them
1271 if (preg_match_all("/\[img=([^\[\]]*)\]([^\[\]]*)\[\/img\]/Usi", $body, $pictures, PREG_SET_ORDER)) {
1272 foreach ($pictures as $picture) {
1273 $imgdata = Images::getInfoFromURLCached($picture[1]);
1275 $attachments[] = ['type' => 'Document',
1276 'mediaType' => $imgdata['mime'],
1277 'url' => $picture[1],
1278 'name' => $picture[2]];
1283 return $attachments;
1287 * Callback function to replace a Friendica style mention in a mention that is used on AP
1289 * @param array $match Matching values for the callback
1290 * @return string Replaced mention
1291 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1293 private static function mentionCallback($match)
1295 if (empty($match[1])) {
1299 $data = Contact::getByURL($match[1], false, ['url', 'nick']);
1300 if (empty($data['nick'])) {
1304 return '@[url=' . $data['url'] . ']' . $data['nick'] . '[/url]';
1308 * Remove image elements since they are added as attachment
1310 * @param string $body
1312 * @return string with removed images
1314 private static function removePictures($body)
1316 // Simplify image codes
1317 $body = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '[img]$3[/img]', $body);
1318 $body = preg_replace("/\[img\=(.*?)\](.*?)\[\/img\]/ism", '[img]$1[/img]', $body);
1320 // Now remove local links
1321 $body = preg_replace_callback(
1322 '/\[url=([^\[\]]*)\]\[img\](.*)\[\/img\]\[\/url\]/Usi',
1324 // We remove the link when it is a link to a local photo page
1325 if (Photo::isLocalPage($match[1])) {
1328 // otherwise we just return the link
1329 return '[url]' . $match[1] . '[/url]';
1334 // Remove all pictures
1335 $body = preg_replace("/\[img\]([^\[\]]*)\[\/img\]/Usi", '', $body);
1341 * Fetches the "context" value for a givem item array from the "conversation" table
1343 * @param array $item
1345 * @return string with context url
1346 * @throws \Exception
1348 private static function fetchContextURLForItem($item)
1350 $conversation = DBA::selectFirst('conversation', ['conversation-href', 'conversation-uri'], ['item-uri' => $item['parent-uri']]);
1351 if (DBA::isResult($conversation) && !empty($conversation['conversation-href'])) {
1352 $context_uri = $conversation['conversation-href'];
1353 } elseif (DBA::isResult($conversation) && !empty($conversation['conversation-uri'])) {
1354 $context_uri = $conversation['conversation-uri'];
1356 $context_uri = $item['parent-uri'] . '#context';
1358 return $context_uri;
1362 * Returns if the post contains sensitive content ("nsfw")
1364 * @param integer $uri_id
1367 * @throws \Exception
1369 private static function isSensitive($uri_id)
1371 return DBA::exists('tag-view', ['uri-id' => $uri_id, 'name' => 'nsfw']);
1375 * Creates event data
1377 * @param array $item
1379 * @return array with the event data
1380 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1382 public static function createEvent($item)
1385 $event['name'] = $item['event-summary'];
1386 $event['content'] = BBCode::convert($item['event-desc'], false, BBCode::ACTIVITYPUB);
1387 $event['startTime'] = DateTimeFormat::utc($item['event-start'] . '+00:00', DateTimeFormat::ATOM);
1389 if (!$item['event-nofinish']) {
1390 $event['endTime'] = DateTimeFormat::utc($item['event-finish'] . '+00:00', DateTimeFormat::ATOM);
1393 if (!empty($item['event-location'])) {
1394 $item['location'] = $item['event-location'];
1395 $event['location'] = self::createLocation($item);
1402 * Creates a note/article object array
1404 * @param array $item
1406 * @return array with the object data
1407 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1408 * @throws \ImagickException
1410 public static function createNote($item)
1416 if ($item['event-type'] == 'event') {
1418 } elseif (!empty($item['title'])) {
1424 if ($item['deleted']) {
1425 $type = 'Tombstone';
1429 $data['id'] = $item['uri'];
1430 $data['type'] = $type;
1432 if ($item['deleted']) {
1436 $data['summary'] = BBCode::toPlaintext(BBCode::getAbstract($item['body'], Protocol::ACTIVITYPUB));
1438 if ($item['uri'] != $item['thr-parent']) {
1439 $data['inReplyTo'] = $item['thr-parent'];
1441 $data['inReplyTo'] = null;
1444 $data['diaspora:guid'] = $item['guid'];
1445 $data['published'] = DateTimeFormat::utc($item['created'] . '+00:00', DateTimeFormat::ATOM);
1447 if ($item['created'] != $item['edited']) {
1448 $data['updated'] = DateTimeFormat::utc($item['edited'] . '+00:00', DateTimeFormat::ATOM);
1451 $data['url'] = $item['plink'];
1452 $data['attributedTo'] = $item['author-link'];
1453 $data['sensitive'] = self::isSensitive($item['uri-id']);
1454 $data['context'] = self::fetchContextURLForItem($item);
1456 if (!empty($item['title'])) {
1457 $data['name'] = BBCode::toPlaintext($item['title'], false);
1460 $permission_block = self::createPermissionBlockForItem($item, false);
1462 $body = $item['body'];
1464 if (empty($item['uid']) || !Feature::isEnabled($item['uid'], 'explicit_mentions')) {
1465 $body = self::prependMentions($body, $item['uri-id']);
1468 if ($type == 'Note') {
1469 $body = self::removePictures($body);
1470 } elseif (($type == 'Article') && empty($data['summary'])) {
1471 $data['summary'] = BBCode::toPlaintext(Plaintext::shorten(self::removePictures($body), 1000));
1474 if ($type == 'Event') {
1475 $data = array_merge($data, self::createEvent($item));
1477 $regexp = "/[@!]\[url\=([^\[\]]*)\].*?\[\/url\]/ism";
1478 $body = preg_replace_callback($regexp, ['self', 'mentionCallback'], $body);
1480 $data['content'] = BBCode::convert($body, false, BBCode::ACTIVITYPUB);
1483 // The regular "content" field does contain a minimized HTML. This is done since systems like
1484 // Mastodon has got problems with - for example - embedded pictures.
1485 // The contentMap does contain the unmodified HTML.
1486 $language = self::getLanguage($item);
1487 if (!empty($language)) {
1488 $regexp = "/[@!]\[url\=([^\[\]]*)\].*?\[\/url\]/ism";
1489 $richbody = preg_replace_callback($regexp, ['self', 'mentionCallback'], $item['body']);
1490 $richbody = BBCode::removeAttachment($richbody);
1492 $data['contentMap'][$language] = BBCode::convert($richbody, false);
1495 $data['source'] = ['content' => $item['body'], 'mediaType' => "text/bbcode"];
1497 if (!empty($item['signed_text']) && ($item['uri'] != $item['thr-parent'])) {
1498 $data['diaspora:comment'] = $item['signed_text'];
1501 $data['attachment'] = self::createAttachmentList($item, $type);
1502 $data['tag'] = self::createTagList($item);
1504 if (empty($data['location']) && (!empty($item['coord']) || !empty($item['location']))) {
1505 $data['location'] = self::createLocation($item);
1508 if (!empty($item['app'])) {
1509 $data['generator'] = ['type' => 'Application', 'name' => $item['app']];
1512 $data = array_merge($data, $permission_block);
1518 * Fetches the language from the post, the user or the system.
1520 * @param array $item
1522 * @return string language string
1524 private static function getLanguage(array $item)
1526 // Try to fetch the language from the post itself
1527 if (!empty($item['language'])) {
1528 $languages = array_keys(json_decode($item['language'], true));
1529 if (!empty($languages[0])) {
1530 return $languages[0];
1534 // Otherwise use the user's language
1535 if (!empty($item['uid'])) {
1536 $user = DBA::selectFirst('user', ['language'], ['uid' => $item['uid']]);
1537 if (!empty($user['language'])) {
1538 return $user['language'];
1542 // And finally just use the system language
1543 return DI::config()->get('system', 'language');
1547 * Creates an an "add tag" entry
1549 * @param array $item
1550 * @param array $data activity data
1552 * @return array with activity data for adding tags
1553 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1554 * @throws \ImagickException
1556 private static function createAddTag($item, $data)
1558 $object = XML::parseString($item['object']);
1559 $target = XML::parseString($item["target"]);
1561 $data['diaspora:guid'] = $item['guid'];
1562 $data['actor'] = $item['author-link'];
1563 $data['target'] = (string)$target->id;
1564 $data['summary'] = BBCode::toPlaintext($item['body']);
1565 $data['object'] = ['id' => (string)$object->id, 'type' => 'tag', 'name' => (string)$object->title, 'content' => (string)$object->content];
1571 * Creates an announce object entry
1573 * @param array $item
1574 * @param array $data activity data
1576 * @return array with activity data
1577 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1578 * @throws \ImagickException
1580 private static function createAnnounce($item, $data)
1582 $orig_body = $item['body'];
1583 $announce = self::getAnnounceArray($item);
1584 if (empty($announce)) {
1585 $data['type'] = 'Create';
1586 $data['object'] = self::createNote($item);
1590 if (empty($announce['comment'])) {
1591 // Pure announce, without a quote
1592 $data['type'] = 'Announce';
1593 $data['object'] = $announce['object']['uri'];
1598 $data['type'] = 'Create';
1599 $item['body'] = $announce['comment'] . "\n" . $announce['object']['plink'];
1600 $data['object'] = self::createNote($item);
1602 /// @todo Finally descide how to implement this in AP. This is a possible way:
1603 $data['object']['attachment'][] = self::createNote($announce['object']);
1605 $data['object']['source']['content'] = $orig_body;
1610 * Return announce related data if the item is an annunce
1612 * @param array $item
1616 public static function getAnnounceArray($item)
1618 $reshared = Item::getShareArray($item);
1619 if (empty($reshared['guid'])) {
1623 $reshared_item = Item::selectFirst([], ['guid' => $reshared['guid']]);
1624 if (!DBA::isResult($reshared_item)) {
1628 if (!in_array($reshared_item['network'], [Protocol::ACTIVITYPUB, Protocol::DFRN])) {
1632 $profile = APContact::getByURL($reshared_item['author-link'], false);
1633 if (empty($profile)) {
1637 return ['object' => $reshared_item, 'actor' => $profile, 'comment' => $reshared['comment']];
1641 * Checks if the provided item array is an announce
1643 * @param array $item
1647 public static function isAnnounce($item)
1649 if (!empty($item['verb']) && ($item['verb'] == Activity::ANNOUNCE)) {
1653 $announce = self::getAnnounceArray($item);
1654 if (empty($announce)) {
1658 return empty($announce['comment']);
1662 * Creates an activity id for a given contact id
1664 * @param integer $cid Contact ID of target
1666 * @return bool|string activity id
1668 public static function activityIDFromContact($cid)
1670 $contact = DBA::selectFirst('contact', ['uid', 'id', 'created'], ['id' => $cid]);
1671 if (!DBA::isResult($contact)) {
1675 $hash = hash('ripemd128', $contact['uid'].'-'.$contact['id'].'-'.$contact['created']);
1676 $uuid = substr($hash, 0, 8). '-' . substr($hash, 8, 4) . '-' . substr($hash, 12, 4) . '-' . substr($hash, 16, 4) . '-' . substr($hash, 20, 12);
1677 return DI::baseUrl() . '/activity/' . $uuid;
1681 * Transmits a contact suggestion to a given inbox
1683 * @param integer $uid User ID
1684 * @param string $inbox Target inbox
1685 * @param integer $suggestion_id Suggestion ID
1687 * @return boolean was the transmission successful?
1688 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1690 public static function sendContactSuggestion($uid, $inbox, $suggestion_id)
1692 $owner = User::getOwnerDataById($uid);
1694 $suggestion = DI::fsuggest()->getById($suggestion_id);
1696 $data = ['@context' => ActivityPub::CONTEXT,
1697 'id' => DI::baseUrl() . '/activity/' . System::createGUID(),
1698 'type' => 'Announce',
1699 'actor' => $owner['url'],
1700 'object' => $suggestion->url,
1701 'content' => $suggestion->note,
1702 'instrument' => self::getService(),
1703 'to' => [ActivityPub::PUBLIC_COLLECTION],
1706 $signed = LDSignature::sign($data, $owner);
1708 Logger::log('Deliver profile deletion for user ' . $uid . ' to ' . $inbox . ' via ActivityPub', Logger::DEBUG);
1709 return HTTPSignature::transmit($signed, $inbox, $uid);
1713 * Transmits a profile relocation to a given inbox
1715 * @param integer $uid User ID
1716 * @param string $inbox Target inbox
1718 * @return boolean was the transmission successful?
1719 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1721 public static function sendProfileRelocation($uid, $inbox)
1723 $owner = User::getOwnerDataById($uid);
1725 $data = ['@context' => ActivityPub::CONTEXT,
1726 'id' => DI::baseUrl() . '/activity/' . System::createGUID(),
1727 'type' => 'dfrn:relocate',
1728 'actor' => $owner['url'],
1729 'object' => $owner['url'],
1730 'published' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
1731 'instrument' => self::getService(),
1732 'to' => [ActivityPub::PUBLIC_COLLECTION],
1735 $signed = LDSignature::sign($data, $owner);
1737 Logger::log('Deliver profile relocation for user ' . $uid . ' to ' . $inbox . ' via ActivityPub', Logger::DEBUG);
1738 return HTTPSignature::transmit($signed, $inbox, $uid);
1742 * Transmits a profile deletion to a given inbox
1744 * @param integer $uid User ID
1745 * @param string $inbox Target inbox
1747 * @return boolean was the transmission successful?
1748 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1750 public static function sendProfileDeletion($uid, $inbox)
1752 $owner = User::getOwnerDataById($uid);
1754 if (empty($owner)) {
1755 Logger::error('No owner data found, the deletion message cannot be processed.', ['user' => $uid]);
1759 if (empty($owner['uprvkey'])) {
1760 Logger::error('No private key for owner found, the deletion message cannot be processed.', ['user' => $uid]);
1764 $data = ['@context' => ActivityPub::CONTEXT,
1765 'id' => DI::baseUrl() . '/activity/' . System::createGUID(),
1767 'actor' => $owner['url'],
1768 'object' => $owner['url'],
1769 'published' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
1770 'instrument' => self::getService(),
1771 'to' => [ActivityPub::PUBLIC_COLLECTION],
1774 $signed = LDSignature::sign($data, $owner);
1776 Logger::log('Deliver profile deletion for user ' . $uid . ' to ' . $inbox . ' via ActivityPub', Logger::DEBUG);
1777 return HTTPSignature::transmit($signed, $inbox, $uid);
1781 * Transmits a profile change to a given inbox
1783 * @param integer $uid User ID
1784 * @param string $inbox Target inbox
1786 * @return boolean was the transmission successful?
1787 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1788 * @throws \ImagickException
1790 public static function sendProfileUpdate($uid, $inbox)
1792 $owner = User::getOwnerDataById($uid);
1793 $profile = APContact::getByURL($owner['url']);
1795 $data = ['@context' => ActivityPub::CONTEXT,
1796 'id' => DI::baseUrl() . '/activity/' . System::createGUID(),
1798 'actor' => $owner['url'],
1799 'object' => self::getProfile($uid),
1800 'published' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
1801 'instrument' => self::getService(),
1802 'to' => [$profile['followers']],
1805 $signed = LDSignature::sign($data, $owner);
1807 Logger::log('Deliver profile update for user ' . $uid . ' to ' . $inbox . ' via ActivityPub', Logger::DEBUG);
1808 return HTTPSignature::transmit($signed, $inbox, $uid);
1812 * Transmits a given activity to a target
1814 * @param string $activity Type name
1815 * @param string $target Target profile
1816 * @param integer $uid User ID
1818 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1819 * @throws \ImagickException
1820 * @throws \Exception
1822 public static function sendActivity($activity, $target, $uid, $id = '')
1824 $profile = APContact::getByURL($target);
1825 if (empty($profile['inbox'])) {
1826 Logger::warning('No inbox found for target', ['target' => $target, 'profile' => $profile]);
1830 $owner = User::getOwnerDataById($uid);
1833 $id = DI::baseUrl() . '/activity/' . System::createGUID();
1836 $data = ['@context' => ActivityPub::CONTEXT,
1838 'type' => $activity,
1839 'actor' => $owner['url'],
1840 'object' => $profile['url'],
1841 'instrument' => self::getService(),
1842 'to' => [$profile['url']]];
1844 Logger::log('Sending activity ' . $activity . ' to ' . $target . ' for user ' . $uid, Logger::DEBUG);
1846 $signed = LDSignature::sign($data, $owner);
1847 return HTTPSignature::transmit($signed, $profile['inbox'], $uid);
1851 * Transmits a "follow object" activity to a target
1852 * This is a preparation for sending automated "follow" requests when receiving "Announce" messages
1854 * @param string $object Object URL
1855 * @param string $target Target profile
1856 * @param integer $uid User ID
1858 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1859 * @throws \ImagickException
1860 * @throws \Exception
1862 public static function sendFollowObject($object, $target, $uid = 0)
1864 $profile = APContact::getByURL($target);
1865 if (empty($profile['inbox'])) {
1866 Logger::warning('No inbox found for target', ['target' => $target, 'profile' => $profile]);
1871 // Fetch the list of administrators
1872 $admin_mail = explode(',', str_replace(' ', '', DI::config()->get('config', 'admin_email')));
1874 // We need to use some user as a sender. It doesn't care who it will send. We will use an administrator account.
1875 $condition = ['verified' => true, 'blocked' => false, 'account_removed' => false, 'account_expired' => false, 'email' => $admin_mail];
1876 $first_user = DBA::selectFirst('user', ['uid'], $condition);
1877 $uid = $first_user['uid'];
1880 $condition = ['verb' => Activity::FOLLOW, 'uid' => 0, 'parent-uri' => $object,
1881 'author-id' => Contact::getPublicIdByUserId($uid)];
1882 if (Item::exists($condition)) {
1883 Logger::log('Follow for ' . $object . ' for user ' . $uid . ' does already exist.', Logger::DEBUG);
1887 $owner = User::getOwnerDataById($uid);
1889 $data = ['@context' => ActivityPub::CONTEXT,
1890 'id' => DI::baseUrl() . '/activity/' . System::createGUID(),
1892 'actor' => $owner['url'],
1893 'object' => $object,
1894 'instrument' => self::getService(),
1895 'to' => [$profile['url']]];
1897 Logger::log('Sending follow ' . $object . ' to ' . $target . ' for user ' . $uid, Logger::DEBUG);
1899 $signed = LDSignature::sign($data, $owner);
1900 return HTTPSignature::transmit($signed, $profile['inbox'], $uid);
1904 * Transmit a message that the contact request had been accepted
1906 * @param string $target Target profile
1908 * @param integer $uid User ID
1909 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1910 * @throws \ImagickException
1912 public static function sendContactAccept($target, $id, $uid)
1914 $profile = APContact::getByURL($target);
1915 if (empty($profile['inbox'])) {
1916 Logger::warning('No inbox found for target', ['target' => $target, 'profile' => $profile]);
1920 $owner = User::getOwnerDataById($uid);
1921 $data = ['@context' => ActivityPub::CONTEXT,
1922 'id' => DI::baseUrl() . '/activity/' . System::createGUID(),
1924 'actor' => $owner['url'],
1926 'id' => (string)$id,
1928 'actor' => $profile['url'],
1929 'object' => $owner['url']
1931 'instrument' => self::getService(),
1932 'to' => [$profile['url']]];
1934 Logger::debug('Sending accept to ' . $target . ' for user ' . $uid . ' with id ' . $id);
1936 $signed = LDSignature::sign($data, $owner);
1937 HTTPSignature::transmit($signed, $profile['inbox'], $uid);
1941 * Reject a contact request or terminates the contact relation
1943 * @param string $target Target profile
1945 * @param integer $uid User ID
1946 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1947 * @throws \ImagickException
1949 public static function sendContactReject($target, $id, $uid)
1951 $profile = APContact::getByURL($target);
1952 if (empty($profile['inbox'])) {
1953 Logger::warning('No inbox found for target', ['target' => $target, 'profile' => $profile]);
1957 $owner = User::getOwnerDataById($uid);
1958 $data = ['@context' => ActivityPub::CONTEXT,
1959 'id' => DI::baseUrl() . '/activity/' . System::createGUID(),
1961 'actor' => $owner['url'],
1963 'id' => (string)$id,
1965 'actor' => $profile['url'],
1966 'object' => $owner['url']
1968 'instrument' => self::getService(),
1969 'to' => [$profile['url']]];
1971 Logger::debug('Sending reject to ' . $target . ' for user ' . $uid . ' with id ' . $id);
1973 $signed = LDSignature::sign($data, $owner);
1974 HTTPSignature::transmit($signed, $profile['inbox'], $uid);
1978 * Transmits a message that we don't want to follow this contact anymore
1980 * @param string $target Target profile
1981 * @param integer $uid User ID
1982 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1983 * @throws \ImagickException
1984 * @throws \Exception
1985 * @return bool success
1987 public static function sendContactUndo($target, $cid, $uid)
1989 $profile = APContact::getByURL($target);
1990 if (empty($profile['inbox'])) {
1991 Logger::warning('No inbox found for target', ['target' => $target, 'profile' => $profile]);
1995 $object_id = self::activityIDFromContact($cid);
1996 if (empty($object_id)) {
2000 $id = DI::baseUrl() . '/activity/' . System::createGUID();
2002 $owner = User::getOwnerDataById($uid);
2003 $data = ['@context' => ActivityPub::CONTEXT,
2006 'actor' => $owner['url'],
2007 'object' => ['id' => $object_id, 'type' => 'Follow',
2008 'actor' => $owner['url'],
2009 'object' => $profile['url']],
2010 'instrument' => self::getService(),
2011 'to' => [$profile['url']]];
2013 Logger::log('Sending undo to ' . $target . ' for user ' . $uid . ' with id ' . $id, Logger::DEBUG);
2015 $signed = LDSignature::sign($data, $owner);
2016 return HTTPSignature::transmit($signed, $profile['inbox'], $uid);
2019 private static function prependMentions($body, int $uriid)
2023 foreach (Tag::getByURIId($uriid, [Tag::IMPLICIT_MENTION]) as $tag) {
2024 $profile = Contact::getByURL($tag['url'], false, ['addr', 'contact-type', 'nick']);
2025 if (!empty($profile['addr'])
2026 && $profile['contact-type'] != Contact::TYPE_COMMUNITY
2027 && !strstr($body, $profile['addr'])
2028 && !strstr($body, $tag['url'])
2030 $mentions[] = '@[url=' . $tag['url'] . ']' . $profile['nick'] . '[/url]';
2034 $mentions[] = $body;
2036 return implode(' ', $mentions);