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);
858 $object = self::createNote($mail);
861 $data = ['@context' => ActivityPub::CONTEXT];
866 $data['id'] = $mail['uri'] . '/Create';
867 $data['type'] = 'Create';
868 $data['actor'] = $mail['author-link'];
869 $data['published'] = DateTimeFormat::utc($mail['created'] . '+00:00', DateTimeFormat::ATOM);
870 $data['instrument'] = self::getService();
871 $data = array_merge($data, self::createPermissionBlockForItem($mail, true));
873 if (empty($data['to']) && !empty($data['cc'])) {
874 $data['to'] = $data['cc'];
877 if (empty($data['to']) && !empty($data['bcc'])) {
878 $data['to'] = $data['bcc'];
884 $object['to'] = $data['to'];
885 $object['tag'] = [['type' => 'Mention', 'href' => $object['to'][0], 'name' => '']];
887 unset($object['cc']);
888 unset($object['bcc']);
890 $data['directMessage'] = true;
892 $data['object'] = $object;
894 $owner = User::getOwnerDataById($mail['uid']);
896 if (!$object_mode && !empty($owner)) {
897 return LDSignature::sign($data, $owner);
904 * Returns the activity type of a given item
908 * @return string with activity type
909 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
910 * @throws \ImagickException
912 private static function getTypeOfItem($item)
916 // Only check for a reshare, if it is a real reshare and no quoted reshare
917 if (strpos($item['body'], "[share") === 0) {
918 $announce = self::getAnnounceArray($item);
919 $reshared = !empty($announce);
924 } elseif ($item['verb'] == Activity::POST) {
925 if ($item['created'] == $item['edited']) {
930 } elseif ($item['verb'] == Activity::LIKE) {
932 } elseif ($item['verb'] == Activity::DISLIKE) {
934 } elseif ($item['verb'] == Activity::ATTEND) {
936 } elseif ($item['verb'] == Activity::ATTENDNO) {
938 } elseif ($item['verb'] == Activity::ATTENDMAYBE) {
939 $type = 'TentativeAccept';
940 } elseif ($item['verb'] == Activity::FOLLOW) {
942 } elseif ($item['verb'] == Activity::TAG) {
944 } elseif ($item['verb'] == Activity::ANNOUNCE) {
954 * Creates the activity or fetches it from the cache
956 * @param integer $item_id
957 * @param boolean $force Force new cache entry
959 * @return array with the activity
962 public static function createCachedActivityFromItem($item_id, $force = false)
964 $cachekey = 'APDelivery:createActivity:' . $item_id;
967 $data = DI::cache()->get($cachekey);
968 if (!is_null($data)) {
973 $data = self::createActivityFromItem($item_id);
975 DI::cache()->set($cachekey, $data, Duration::QUARTER_HOUR);
980 * Creates an activity array for a given item id
982 * @param integer $item_id
983 * @param boolean $object_mode Is the activity item is used inside another object?
985 * @return array of activity
988 public static function createActivityFromItem($item_id, $object_mode = false)
990 Logger::info('Fetching activity', ['item' => $item_id]);
991 $item = Item::selectFirst([], ['id' => $item_id, 'parent-network' => Protocol::NATIVE_SUPPORT]);
992 if (!DBA::isResult($item)) {
996 // In case of a forum post ensure to return the original post if author and forum are on the same machine
997 if (!empty($item['forum_mode'])) {
998 $author = Contact::getById($item['author-id'], ['nurl']);
999 if (!empty($author['nurl'])) {
1000 $self = Contact::selectFirst(['uid'], ['nurl' => $author['nurl'], 'self' => true]);
1001 if (!empty($self['uid'])) {
1002 $item = Item::selectFirst([], ['uri-id' => $item['uri-id'], 'uid' => $self['uid']]);
1008 $condition = ['item-uri' => $item['uri'], 'protocol' => Conversation::PARCEL_ACTIVITYPUB];
1009 $conversation = DBA::selectFirst('conversation', ['source'], $condition);
1010 if (DBA::isResult($conversation)) {
1011 $data = json_decode($conversation['source'], true);
1012 if (!empty($data['type'])) {
1013 if (in_array($data['type'], ['Create', 'Update'])) {
1015 unset($data['@context']);
1016 unset($data['signature']);
1018 Logger::info('Return stored conversation', ['item' => $item_id]);
1020 } elseif (in_array('as:' . $data['type'], Receiver::CONTENT_TYPES)) {
1021 if (!empty($data['@context'])) {
1022 $context = $data['@context'];
1023 unset($data['@context']);
1025 unset($data['actor']);
1031 $type = self::getTypeOfItem($item);
1034 if (!$object_mode) {
1035 $data = ['@context' => $context ?? ActivityPub::CONTEXT];
1037 if ($item['deleted'] && ($item['gravity'] == GRAVITY_ACTIVITY)) {
1039 } elseif ($item['deleted']) {
1046 if (($item['gravity'] == GRAVITY_ACTIVITY) && ($type != 'Undo')) {
1047 $data['id'] = $item['uri'];
1049 $data['id'] = $item['uri'] . '/' . $type;
1052 $data['type'] = $type;
1054 if (($type != 'Announce') || ($item['gravity'] != GRAVITY_PARENT)) {
1055 $data['actor'] = $item['author-link'];
1057 $data['actor'] = $item['owner-link'];
1060 $data['published'] = DateTimeFormat::utc($item['created'] . '+00:00', DateTimeFormat::ATOM);
1062 $data['instrument'] = self::getService();
1064 $data = array_merge($data, self::createPermissionBlockForItem($item, false));
1066 if (in_array($data['type'], ['Create', 'Update', 'Delete'])) {
1067 $data['object'] = $object ?? self::createNote($item);
1068 } elseif ($data['type'] == 'Add') {
1069 $data = self::createAddTag($item, $data);
1070 } elseif ($data['type'] == 'Announce') {
1071 if ($item['verb'] == ACTIVITY::ANNOUNCE) {
1072 $data['object'] = $item['thr-parent'];
1074 $data = self::createAnnounce($item, $data);
1076 } elseif ($data['type'] == 'Follow') {
1077 $data['object'] = $item['parent-uri'];
1078 } elseif ($data['type'] == 'Undo') {
1079 $data['object'] = self::createActivityFromItem($item_id, true);
1081 $data['diaspora:guid'] = $item['guid'];
1082 if (!empty($item['signed_text'])) {
1083 $data['diaspora:like'] = $item['signed_text'];
1085 $data['object'] = $item['thr-parent'];
1088 if (!empty($item['contact-uid'])) {
1089 $uid = $item['contact-uid'];
1091 $uid = $item['uid'];
1094 $owner = User::getOwnerDataById($uid);
1096 Logger::info('Fetched activity', ['item' => $item_id, 'uid' => $uid]);
1098 // We don't sign if we aren't the actor. This is important for relaying content especially for forums
1099 if (!$object_mode && !empty($owner) && ($data['actor'] == $owner['url'])) {
1100 return LDSignature::sign($data, $owner);
1105 /// @todo Create "conversation" entry
1109 * Creates a location entry for a given item array
1111 * @param array $item
1113 * @return array with location array
1115 private static function createLocation($item)
1117 $location = ['type' => 'Place'];
1119 if (!empty($item['location'])) {
1120 $location['name'] = $item['location'];
1125 if (empty($item['coord'])) {
1126 $coord = Map::getCoordinates($item['location']);
1128 $coords = explode(' ', $item['coord']);
1129 if (count($coords) == 2) {
1130 $coord = ['lat' => $coords[0], 'lon' => $coords[1]];
1134 if (!empty($coord['lat']) && !empty($coord['lon'])) {
1135 $location['latitude'] = $coord['lat'];
1136 $location['longitude'] = $coord['lon'];
1143 * Returns a tag array for a given item array
1145 * @param array $item
1147 * @return array of tags
1148 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1150 private static function createTagList($item)
1154 $terms = Tag::getByURIId($item['uri-id'], [Tag::HASHTAG, Tag::MENTION, Tag::IMPLICIT_MENTION, Tag::EXCLUSIVE_MENTION]);
1155 foreach ($terms as $term) {
1156 if ($term['type'] == Tag::HASHTAG) {
1157 $url = DI::baseUrl() . '/search?tag=' . urlencode($term['name']);
1158 $tags[] = ['type' => 'Hashtag', 'href' => $url, 'name' => '#' . $term['name']];
1160 $contact = Contact::getByURL($term['url'], false, ['addr']);
1161 if (empty($contact)) {
1164 if (!empty($contact['addr'])) {
1165 $mention = '@' . $contact['addr'];
1167 $mention = '@' . $term['url'];
1170 $tags[] = ['type' => 'Mention', 'href' => $term['url'], 'name' => $mention];
1174 $announce = self::getAnnounceArray($item);
1175 // Mention the original author upon commented reshares
1176 if (!empty($announce['comment'])) {
1177 $tags[] = ['type' => 'Mention', 'href' => $announce['actor']['url'], 'name' => '@' . $announce['actor']['addr']];
1184 * Adds attachment data to the JSON document
1186 * @param array $item Data of the item that is to be posted
1187 * @param string $type Object type
1189 * @return array with attachment data
1190 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1192 private static function createAttachmentList($item, $type)
1196 // Currently deactivated, since it creates side effects on Mastodon and Pleroma.
1197 // It will be reactivated, once this cleared.
1199 $attach_data = BBCode::getAttachmentData($item['body']);
1200 if (!empty($attach_data['url'])) {
1201 $attachment = ['type' => 'Page',
1202 'mediaType' => 'text/html',
1203 'url' => $attach_data['url']];
1205 if (!empty($attach_data['title'])) {
1206 $attachment['name'] = $attach_data['title'];
1209 if (!empty($attach_data['description'])) {
1210 $attachment['summary'] = $attach_data['description'];
1213 if (!empty($attach_data['image'])) {
1214 $imgdata = Images::getInfoFromURLCached($attach_data['image']);
1216 $attachment['icon'] = ['type' => 'Image',
1217 'mediaType' => $imgdata['mime'],
1218 'width' => $imgdata[0],
1219 'height' => $imgdata[1],
1220 'url' => $attach_data['image']];
1224 $attachments[] = $attachment;
1227 $arr = explode('[/attach],', $item['attach']);
1229 foreach ($arr as $r) {
1231 $cnt = preg_match('|\[attach\]href=\"(.*?)\" length=\"(.*?)\" type=\"(.*?)\" title=\"(.*?)\"|', $r, $matches);
1233 $attributes = ['type' => 'Document',
1234 'mediaType' => $matches[3],
1235 'url' => $matches[1],
1238 if (trim($matches[4]) != '') {
1239 $attributes['name'] = trim($matches[4]);
1242 $attachments[] = $attributes;
1247 if ($type != 'Note') {
1248 return $attachments;
1251 // Simplify image codes
1252 $body = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '[img]$3[/img]', $item['body']);
1254 // Grab all pictures without alternative descriptions and create attachments out of them
1255 if (preg_match_all("/\[img\]([^\[\]]*)\[\/img\]/Usi", $body, $pictures)) {
1256 foreach ($pictures[1] as $picture) {
1257 $imgdata = Images::getInfoFromURLCached($picture);
1259 $attachments[] = ['type' => 'Document',
1260 'mediaType' => $imgdata['mime'],
1267 // Grab all pictures with alternative description and create attachments out of them
1268 if (preg_match_all("/\[img=([^\[\]]*)\]([^\[\]]*)\[\/img\]/Usi", $body, $pictures, PREG_SET_ORDER)) {
1269 foreach ($pictures as $picture) {
1270 $imgdata = Images::getInfoFromURLCached($picture[1]);
1272 $attachments[] = ['type' => 'Document',
1273 'mediaType' => $imgdata['mime'],
1274 'url' => $picture[1],
1275 'name' => $picture[2]];
1280 return $attachments;
1284 * Callback function to replace a Friendica style mention in a mention that is used on AP
1286 * @param array $match Matching values for the callback
1287 * @return string Replaced mention
1288 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1290 private static function mentionCallback($match)
1292 if (empty($match[1])) {
1296 $data = Contact::getByURL($match[1], false, ['url', 'nick']);
1297 if (empty($data['nick'])) {
1301 return '@[url=' . $data['url'] . ']' . $data['nick'] . '[/url]';
1305 * Remove image elements since they are added as attachment
1307 * @param string $body
1309 * @return string with removed images
1311 private static function removePictures($body)
1313 // Simplify image codes
1314 $body = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '[img]$3[/img]', $body);
1315 $body = preg_replace("/\[img\=(.*?)\](.*?)\[\/img\]/ism", '[img]$1[/img]', $body);
1317 // Now remove local links
1318 $body = preg_replace_callback(
1319 '/\[url=([^\[\]]*)\]\[img\](.*)\[\/img\]\[\/url\]/Usi',
1321 // We remove the link when it is a link to a local photo page
1322 if (Photo::isLocalPage($match[1])) {
1325 // otherwise we just return the link
1326 return '[url]' . $match[1] . '[/url]';
1331 // Remove all pictures
1332 $body = preg_replace("/\[img\]([^\[\]]*)\[\/img\]/Usi", '', $body);
1338 * Fetches the "context" value for a givem item array from the "conversation" table
1340 * @param array $item
1342 * @return string with context url
1343 * @throws \Exception
1345 private static function fetchContextURLForItem($item)
1347 $conversation = DBA::selectFirst('conversation', ['conversation-href', 'conversation-uri'], ['item-uri' => $item['parent-uri']]);
1348 if (DBA::isResult($conversation) && !empty($conversation['conversation-href'])) {
1349 $context_uri = $conversation['conversation-href'];
1350 } elseif (DBA::isResult($conversation) && !empty($conversation['conversation-uri'])) {
1351 $context_uri = $conversation['conversation-uri'];
1353 $context_uri = $item['parent-uri'] . '#context';
1355 return $context_uri;
1359 * Returns if the post contains sensitive content ("nsfw")
1361 * @param integer $uri_id
1364 * @throws \Exception
1366 private static function isSensitive($uri_id)
1368 return DBA::exists('tag-view', ['uri-id' => $uri_id, 'name' => 'nsfw']);
1372 * Creates event data
1374 * @param array $item
1376 * @return array with the event data
1377 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1379 public static function createEvent($item)
1382 $event['name'] = $item['event-summary'];
1383 $event['content'] = BBCode::convert($item['event-desc'], false, BBCode::ACTIVITYPUB);
1384 $event['startTime'] = DateTimeFormat::utc($item['event-start'] . '+00:00', DateTimeFormat::ATOM);
1386 if (!$item['event-nofinish']) {
1387 $event['endTime'] = DateTimeFormat::utc($item['event-finish'] . '+00:00', DateTimeFormat::ATOM);
1390 if (!empty($item['event-location'])) {
1391 $item['location'] = $item['event-location'];
1392 $event['location'] = self::createLocation($item);
1399 * Creates a note/article object array
1401 * @param array $item
1403 * @return array with the object data
1404 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1405 * @throws \ImagickException
1407 public static function createNote($item)
1413 if ($item['event-type'] == 'event') {
1415 } elseif (!empty($item['title'])) {
1421 if ($item['deleted']) {
1422 $type = 'Tombstone';
1426 $data['id'] = $item['uri'];
1427 $data['type'] = $type;
1429 if ($item['deleted']) {
1433 $data['summary'] = BBCode::toPlaintext(BBCode::getAbstract($item['body'], Protocol::ACTIVITYPUB));
1435 if ($item['uri'] != $item['thr-parent']) {
1436 $data['inReplyTo'] = $item['thr-parent'];
1438 $data['inReplyTo'] = null;
1441 $data['diaspora:guid'] = $item['guid'];
1442 $data['published'] = DateTimeFormat::utc($item['created'] . '+00:00', DateTimeFormat::ATOM);
1444 if ($item['created'] != $item['edited']) {
1445 $data['updated'] = DateTimeFormat::utc($item['edited'] . '+00:00', DateTimeFormat::ATOM);
1448 $data['url'] = $item['plink'];
1449 $data['attributedTo'] = $item['author-link'];
1450 $data['sensitive'] = self::isSensitive($item['uri-id']);
1451 $data['context'] = self::fetchContextURLForItem($item);
1453 if (!empty($item['title'])) {
1454 $data['name'] = BBCode::toPlaintext($item['title'], false);
1457 $permission_block = self::createPermissionBlockForItem($item, false);
1459 $body = $item['body'];
1461 if (empty($item['uid']) || !Feature::isEnabled($item['uid'], 'explicit_mentions')) {
1462 $body = self::prependMentions($body, $item['uri-id']);
1465 if ($type == 'Note') {
1466 $body = self::removePictures($body);
1467 } elseif (($type == 'Article') && empty($data['summary'])) {
1468 $data['summary'] = BBCode::toPlaintext(Plaintext::shorten(self::removePictures($body), 1000));
1471 if ($type == 'Event') {
1472 $data = array_merge($data, self::createEvent($item));
1474 $regexp = "/[@!]\[url\=([^\[\]]*)\].*?\[\/url\]/ism";
1475 $body = preg_replace_callback($regexp, ['self', 'mentionCallback'], $body);
1477 $data['content'] = BBCode::convert($body, false, BBCode::ACTIVITYPUB);
1480 // The regular "content" field does contain a minimized HTML. This is done since systems like
1481 // Mastodon has got problems with - for example - embedded pictures.
1482 // The contentMap does contain the unmodified HTML.
1483 $language = self::getLanguage($item);
1484 if (!empty($language)) {
1485 $regexp = "/[@!]\[url\=([^\[\]]*)\].*?\[\/url\]/ism";
1486 $richbody = preg_replace_callback($regexp, ['self', 'mentionCallback'], $item['body']);
1487 $richbody = BBCode::removeAttachment($richbody);
1489 $data['contentMap'][$language] = BBCode::convert($richbody, false);
1492 $data['source'] = ['content' => $item['body'], 'mediaType' => "text/bbcode"];
1494 if (!empty($item['signed_text']) && ($item['uri'] != $item['thr-parent'])) {
1495 $data['diaspora:comment'] = $item['signed_text'];
1498 $data['attachment'] = self::createAttachmentList($item, $type);
1499 $data['tag'] = self::createTagList($item);
1501 if (empty($data['location']) && (!empty($item['coord']) || !empty($item['location']))) {
1502 $data['location'] = self::createLocation($item);
1505 if (!empty($item['app'])) {
1506 $data['generator'] = ['type' => 'Application', 'name' => $item['app']];
1509 $data = array_merge($data, $permission_block);
1515 * Fetches the language from the post, the user or the system.
1517 * @param array $item
1519 * @return string language string
1521 private static function getLanguage(array $item)
1523 // Try to fetch the language from the post itself
1524 if (!empty($item['language'])) {
1525 $languages = array_keys(json_decode($item['language'], true));
1526 if (!empty($languages[0])) {
1527 return $languages[0];
1531 // Otherwise use the user's language
1532 if (!empty($item['uid'])) {
1533 $user = DBA::selectFirst('user', ['language'], ['uid' => $item['uid']]);
1534 if (!empty($user['language'])) {
1535 return $user['language'];
1539 // And finally just use the system language
1540 return DI::config()->get('system', 'language');
1544 * Creates an an "add tag" entry
1546 * @param array $item
1547 * @param array $data activity data
1549 * @return array with activity data for adding tags
1550 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1551 * @throws \ImagickException
1553 private static function createAddTag($item, $data)
1555 $object = XML::parseString($item['object']);
1556 $target = XML::parseString($item["target"]);
1558 $data['diaspora:guid'] = $item['guid'];
1559 $data['actor'] = $item['author-link'];
1560 $data['target'] = (string)$target->id;
1561 $data['summary'] = BBCode::toPlaintext($item['body']);
1562 $data['object'] = ['id' => (string)$object->id, 'type' => 'tag', 'name' => (string)$object->title, 'content' => (string)$object->content];
1568 * Creates an announce object entry
1570 * @param array $item
1571 * @param array $data activity data
1573 * @return array with activity data
1574 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1575 * @throws \ImagickException
1577 private static function createAnnounce($item, $data)
1579 $orig_body = $item['body'];
1580 $announce = self::getAnnounceArray($item);
1581 if (empty($announce)) {
1582 $data['type'] = 'Create';
1583 $data['object'] = self::createNote($item);
1587 if (empty($announce['comment'])) {
1588 // Pure announce, without a quote
1589 $data['type'] = 'Announce';
1590 $data['object'] = $announce['object']['uri'];
1595 $data['type'] = 'Create';
1596 $item['body'] = $announce['comment'] . "\n" . $announce['object']['plink'];
1597 $data['object'] = self::createNote($item);
1599 /// @todo Finally descide how to implement this in AP. This is a possible way:
1600 $data['object']['attachment'][] = self::createNote($announce['object']);
1602 $data['object']['source']['content'] = $orig_body;
1607 * Return announce related data if the item is an annunce
1609 * @param array $item
1613 public static function getAnnounceArray($item)
1615 $reshared = Item::getShareArray($item);
1616 if (empty($reshared['guid'])) {
1620 $reshared_item = Item::selectFirst([], ['guid' => $reshared['guid']]);
1621 if (!DBA::isResult($reshared_item)) {
1625 if (!in_array($reshared_item['network'], [Protocol::ACTIVITYPUB, Protocol::DFRN])) {
1629 $profile = APContact::getByURL($reshared_item['author-link'], false);
1630 if (empty($profile)) {
1634 return ['object' => $reshared_item, 'actor' => $profile, 'comment' => $reshared['comment']];
1638 * Checks if the provided item array is an announce
1640 * @param array $item
1644 public static function isAnnounce($item)
1646 if (!empty($item['verb']) && ($item['verb'] == Activity::ANNOUNCE)) {
1650 $announce = self::getAnnounceArray($item);
1651 if (empty($announce)) {
1655 return empty($announce['comment']);
1659 * Creates an activity id for a given contact id
1661 * @param integer $cid Contact ID of target
1663 * @return bool|string activity id
1665 public static function activityIDFromContact($cid)
1667 $contact = DBA::selectFirst('contact', ['uid', 'id', 'created'], ['id' => $cid]);
1668 if (!DBA::isResult($contact)) {
1672 $hash = hash('ripemd128', $contact['uid'].'-'.$contact['id'].'-'.$contact['created']);
1673 $uuid = substr($hash, 0, 8). '-' . substr($hash, 8, 4) . '-' . substr($hash, 12, 4) . '-' . substr($hash, 16, 4) . '-' . substr($hash, 20, 12);
1674 return DI::baseUrl() . '/activity/' . $uuid;
1678 * Transmits a contact suggestion to a given inbox
1680 * @param integer $uid User ID
1681 * @param string $inbox Target inbox
1682 * @param integer $suggestion_id Suggestion ID
1684 * @return boolean was the transmission successful?
1685 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1687 public static function sendContactSuggestion($uid, $inbox, $suggestion_id)
1689 $owner = User::getOwnerDataById($uid);
1691 $suggestion = DI::fsuggest()->getById($suggestion_id);
1693 $data = ['@context' => ActivityPub::CONTEXT,
1694 'id' => DI::baseUrl() . '/activity/' . System::createGUID(),
1695 'type' => 'Announce',
1696 'actor' => $owner['url'],
1697 'object' => $suggestion->url,
1698 'content' => $suggestion->note,
1699 'instrument' => self::getService(),
1700 'to' => [ActivityPub::PUBLIC_COLLECTION],
1703 $signed = LDSignature::sign($data, $owner);
1705 Logger::log('Deliver profile deletion for user ' . $uid . ' to ' . $inbox . ' via ActivityPub', Logger::DEBUG);
1706 return HTTPSignature::transmit($signed, $inbox, $uid);
1710 * Transmits a profile relocation to a given inbox
1712 * @param integer $uid User ID
1713 * @param string $inbox Target inbox
1715 * @return boolean was the transmission successful?
1716 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1718 public static function sendProfileRelocation($uid, $inbox)
1720 $owner = User::getOwnerDataById($uid);
1722 $data = ['@context' => ActivityPub::CONTEXT,
1723 'id' => DI::baseUrl() . '/activity/' . System::createGUID(),
1724 'type' => 'dfrn:relocate',
1725 'actor' => $owner['url'],
1726 'object' => $owner['url'],
1727 'published' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
1728 'instrument' => self::getService(),
1729 'to' => [ActivityPub::PUBLIC_COLLECTION],
1732 $signed = LDSignature::sign($data, $owner);
1734 Logger::log('Deliver profile relocation for user ' . $uid . ' to ' . $inbox . ' via ActivityPub', Logger::DEBUG);
1735 return HTTPSignature::transmit($signed, $inbox, $uid);
1739 * Transmits a profile deletion to a given inbox
1741 * @param integer $uid User ID
1742 * @param string $inbox Target inbox
1744 * @return boolean was the transmission successful?
1745 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1747 public static function sendProfileDeletion($uid, $inbox)
1749 $owner = User::getOwnerDataById($uid);
1751 if (empty($owner)) {
1752 Logger::error('No owner data found, the deletion message cannot be processed.', ['user' => $uid]);
1756 if (empty($owner['uprvkey'])) {
1757 Logger::error('No private key for owner found, the deletion message cannot be processed.', ['user' => $uid]);
1761 $data = ['@context' => ActivityPub::CONTEXT,
1762 'id' => DI::baseUrl() . '/activity/' . System::createGUID(),
1764 'actor' => $owner['url'],
1765 'object' => $owner['url'],
1766 'published' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
1767 'instrument' => self::getService(),
1768 'to' => [ActivityPub::PUBLIC_COLLECTION],
1771 $signed = LDSignature::sign($data, $owner);
1773 Logger::log('Deliver profile deletion for user ' . $uid . ' to ' . $inbox . ' via ActivityPub', Logger::DEBUG);
1774 return HTTPSignature::transmit($signed, $inbox, $uid);
1778 * Transmits a profile change to a given inbox
1780 * @param integer $uid User ID
1781 * @param string $inbox Target inbox
1783 * @return boolean was the transmission successful?
1784 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1785 * @throws \ImagickException
1787 public static function sendProfileUpdate($uid, $inbox)
1789 $owner = User::getOwnerDataById($uid);
1790 $profile = APContact::getByURL($owner['url']);
1792 $data = ['@context' => ActivityPub::CONTEXT,
1793 'id' => DI::baseUrl() . '/activity/' . System::createGUID(),
1795 'actor' => $owner['url'],
1796 'object' => self::getProfile($uid),
1797 'published' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
1798 'instrument' => self::getService(),
1799 'to' => [$profile['followers']],
1802 $signed = LDSignature::sign($data, $owner);
1804 Logger::log('Deliver profile update for user ' . $uid . ' to ' . $inbox . ' via ActivityPub', Logger::DEBUG);
1805 return HTTPSignature::transmit($signed, $inbox, $uid);
1809 * Transmits a given activity to a target
1811 * @param string $activity Type name
1812 * @param string $target Target profile
1813 * @param integer $uid User ID
1815 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1816 * @throws \ImagickException
1817 * @throws \Exception
1819 public static function sendActivity($activity, $target, $uid, $id = '')
1821 $profile = APContact::getByURL($target);
1822 if (empty($profile['inbox'])) {
1823 Logger::warning('No inbox found for target', ['target' => $target, 'profile' => $profile]);
1827 $owner = User::getOwnerDataById($uid);
1830 $id = DI::baseUrl() . '/activity/' . System::createGUID();
1833 $data = ['@context' => ActivityPub::CONTEXT,
1835 'type' => $activity,
1836 'actor' => $owner['url'],
1837 'object' => $profile['url'],
1838 'instrument' => self::getService(),
1839 'to' => [$profile['url']]];
1841 Logger::log('Sending activity ' . $activity . ' to ' . $target . ' for user ' . $uid, Logger::DEBUG);
1843 $signed = LDSignature::sign($data, $owner);
1844 return HTTPSignature::transmit($signed, $profile['inbox'], $uid);
1848 * Transmits a "follow object" activity to a target
1849 * This is a preparation for sending automated "follow" requests when receiving "Announce" messages
1851 * @param string $object Object URL
1852 * @param string $target Target profile
1853 * @param integer $uid User ID
1855 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1856 * @throws \ImagickException
1857 * @throws \Exception
1859 public static function sendFollowObject($object, $target, $uid = 0)
1861 $profile = APContact::getByURL($target);
1862 if (empty($profile['inbox'])) {
1863 Logger::warning('No inbox found for target', ['target' => $target, 'profile' => $profile]);
1868 // Fetch the list of administrators
1869 $admin_mail = explode(',', str_replace(' ', '', DI::config()->get('config', 'admin_email')));
1871 // We need to use some user as a sender. It doesn't care who it will send. We will use an administrator account.
1872 $condition = ['verified' => true, 'blocked' => false, 'account_removed' => false, 'account_expired' => false, 'email' => $admin_mail];
1873 $first_user = DBA::selectFirst('user', ['uid'], $condition);
1874 $uid = $first_user['uid'];
1877 $condition = ['verb' => Activity::FOLLOW, 'uid' => 0, 'parent-uri' => $object,
1878 'author-id' => Contact::getPublicIdByUserId($uid)];
1879 if (Item::exists($condition)) {
1880 Logger::log('Follow for ' . $object . ' for user ' . $uid . ' does already exist.', Logger::DEBUG);
1884 $owner = User::getOwnerDataById($uid);
1886 $data = ['@context' => ActivityPub::CONTEXT,
1887 'id' => DI::baseUrl() . '/activity/' . System::createGUID(),
1889 'actor' => $owner['url'],
1890 'object' => $object,
1891 'instrument' => self::getService(),
1892 'to' => [$profile['url']]];
1894 Logger::log('Sending follow ' . $object . ' to ' . $target . ' for user ' . $uid, Logger::DEBUG);
1896 $signed = LDSignature::sign($data, $owner);
1897 return HTTPSignature::transmit($signed, $profile['inbox'], $uid);
1901 * Transmit a message that the contact request had been accepted
1903 * @param string $target Target profile
1905 * @param integer $uid User ID
1906 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1907 * @throws \ImagickException
1909 public static function sendContactAccept($target, $id, $uid)
1911 $profile = APContact::getByURL($target);
1912 if (empty($profile['inbox'])) {
1913 Logger::warning('No inbox found for target', ['target' => $target, 'profile' => $profile]);
1917 $owner = User::getOwnerDataById($uid);
1918 $data = ['@context' => ActivityPub::CONTEXT,
1919 'id' => DI::baseUrl() . '/activity/' . System::createGUID(),
1921 'actor' => $owner['url'],
1923 'id' => (string)$id,
1925 'actor' => $profile['url'],
1926 'object' => $owner['url']
1928 'instrument' => self::getService(),
1929 'to' => [$profile['url']]];
1931 Logger::debug('Sending accept to ' . $target . ' for user ' . $uid . ' with id ' . $id);
1933 $signed = LDSignature::sign($data, $owner);
1934 HTTPSignature::transmit($signed, $profile['inbox'], $uid);
1938 * Reject a contact request or terminates the contact relation
1940 * @param string $target Target profile
1942 * @param integer $uid User ID
1943 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1944 * @throws \ImagickException
1946 public static function sendContactReject($target, $id, $uid)
1948 $profile = APContact::getByURL($target);
1949 if (empty($profile['inbox'])) {
1950 Logger::warning('No inbox found for target', ['target' => $target, 'profile' => $profile]);
1954 $owner = User::getOwnerDataById($uid);
1955 $data = ['@context' => ActivityPub::CONTEXT,
1956 'id' => DI::baseUrl() . '/activity/' . System::createGUID(),
1958 'actor' => $owner['url'],
1960 'id' => (string)$id,
1962 'actor' => $profile['url'],
1963 'object' => $owner['url']
1965 'instrument' => self::getService(),
1966 'to' => [$profile['url']]];
1968 Logger::debug('Sending reject to ' . $target . ' for user ' . $uid . ' with id ' . $id);
1970 $signed = LDSignature::sign($data, $owner);
1971 HTTPSignature::transmit($signed, $profile['inbox'], $uid);
1975 * Transmits a message that we don't want to follow this contact anymore
1977 * @param string $target Target profile
1978 * @param integer $uid User ID
1979 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1980 * @throws \ImagickException
1981 * @throws \Exception
1982 * @return bool success
1984 public static function sendContactUndo($target, $cid, $uid)
1986 $profile = APContact::getByURL($target);
1987 if (empty($profile['inbox'])) {
1988 Logger::warning('No inbox found for target', ['target' => $target, 'profile' => $profile]);
1992 $object_id = self::activityIDFromContact($cid);
1993 if (empty($object_id)) {
1997 $id = DI::baseUrl() . '/activity/' . System::createGUID();
1999 $owner = User::getOwnerDataById($uid);
2000 $data = ['@context' => ActivityPub::CONTEXT,
2003 'actor' => $owner['url'],
2004 'object' => ['id' => $object_id, 'type' => 'Follow',
2005 'actor' => $owner['url'],
2006 'object' => $profile['url']],
2007 'instrument' => self::getService(),
2008 'to' => [$profile['url']]];
2010 Logger::log('Sending undo to ' . $target . ' for user ' . $uid . ' with id ' . $id, Logger::DEBUG);
2012 $signed = LDSignature::sign($data, $owner);
2013 return HTTPSignature::transmit($signed, $profile['inbox'], $uid);
2016 private static function prependMentions($body, int $uriid)
2020 foreach (Tag::getByURIId($uriid, [Tag::IMPLICIT_MENTION]) as $tag) {
2021 $profile = Contact::getByURL($tag['url'], false, ['addr', 'contact-type', 'nick']);
2022 if (!empty($profile['addr'])
2023 && $profile['contact-type'] != Contact::TYPE_COMMUNITY
2024 && !strstr($body, $profile['addr'])
2025 && !strstr($body, $tag['url'])
2027 $mentions[] = '@[url=' . $tag['url'] . ']' . $profile['nick'] . '[/url]';
2031 $mentions[] = $body;
2033 return implode(' ', $mentions);