3 * @copyright Copyright (C) 2010-2021, the Friendica project
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\GServer;
37 use Friendica\Model\Item;
38 use Friendica\Model\ItemURI;
39 use Friendica\Model\Profile;
40 use Friendica\Model\Photo;
41 use Friendica\Model\Post;
42 use Friendica\Model\Tag;
43 use Friendica\Model\User;
44 use Friendica\Protocol\Activity;
45 use Friendica\Protocol\ActivityPub;
46 use Friendica\Protocol\Relay;
47 use Friendica\Util\DateTimeFormat;
48 use Friendica\Util\HTTPSignature;
49 use Friendica\Util\JsonLD;
50 use Friendica\Util\LDSignature;
51 use Friendica\Util\Map;
52 use Friendica\Util\Network;
53 use Friendica\Util\XML;
56 * ActivityPub Transmitter Protocol class
64 * Add relay servers to the list of inboxes
66 * @param array $inboxes
67 * @return array inboxes with added relay servers
69 public static function addRelayServerInboxes(array $inboxes = [])
71 foreach (Relay::getList(['inbox']) as $contact) {
72 $inboxes[$contact['inbox']] = $contact['inbox'];
79 * Add relay servers to the list of inboxes
81 * @param array $inboxes
82 * @return array inboxes with added relay servers
84 public static function addRelayServerInboxesForItem(int $item_id, array $inboxes = [])
86 $item = Post::selectFirst(['uid'], ['id' => $item_id]);
91 $relays = Relay::getDirectRelayList($item_id);
96 foreach ($relays as $relay) {
97 $contact = Contact::getByURLForUser($relay['url'], $item['uid'], false, ['id']);
98 $inboxes[$relay['batch']][] = $contact['id'] ?? 0;
104 * Subscribe to a relay
106 * @param string $url Subscribe actor url
107 * @return bool success
109 public static function sendRelayFollow(string $url)
111 $contact = Contact::getByURL($url);
112 if (empty($contact)) {
116 $activity_id = ActivityPub\Transmitter::activityIDFromContact($contact['id']);
117 $success = ActivityPub\Transmitter::sendActivity('Follow', $url, 0, $activity_id);
119 DBA::update('contact', ['rel' => Contact::FRIEND], ['id' => $contact['id']]);
126 * Unsubscribe from a relay
128 * @param string $url Subscribe actor url
129 * @param bool $force Set the relay status as non follower even if unsubscribe hadn't worked
130 * @return bool success
132 public static function sendRelayUndoFollow(string $url, bool $force = false)
134 $contact = Contact::getByURL($url);
135 if (empty($contact)) {
139 $success = self::sendContactUndo($url, $contact['id'], 0);
140 if ($success || $force) {
141 DBA::update('contact', ['rel' => Contact::NOTHING], ['id' => $contact['id']]);
148 * Collects a list of contacts of the given owner
150 * @param array $owner Owner array
151 * @param int|array $rel The relevant value(s) contact.rel should match
152 * @param string $module The name of the relevant AP endpoint module (followers|following)
153 * @param integer $page Page number
155 * @return array of owners
158 public static function getContacts($owner, $rel, $module, $page = null)
162 'uid' => $owner['uid'],
170 $condition = DBA::buildCondition($parameters);
172 $sql = "SELECT COUNT(*) as `count`
174 JOIN `apcontact` ON `apcontact`.`url` = `contact`.`url`
177 $contacts = DBA::fetchFirst($sql, ...$parameters);
179 $modulePath = '/' . $module . '/';
181 $data = ['@context' => ActivityPub::CONTEXT];
182 $data['id'] = DI::baseUrl() . $modulePath . $owner['nickname'];
183 $data['type'] = 'OrderedCollection';
184 $data['totalItems'] = $contacts['count'];
186 // When we hide our friends we will only show the pure number but don't allow more.
187 $profile = Profile::getByUID($owner['uid']);
188 if (!empty($profile['hide-friends'])) {
193 $data['first'] = DI::baseUrl() . $modulePath . $owner['nickname'] . '?page=1';
195 $data['type'] = 'OrderedCollectionPage';
198 $sql = "SELECT `contact`.`url`
200 JOIN `apcontact` ON `apcontact`.`url` = `contact`.`url`
204 $parameters[] = ($page - 1) * 100;
207 $contacts = DBA::p($sql, ...$parameters);
208 while ($contact = DBA::fetch($contacts)) {
209 $list[] = $contact['url'];
211 DBA::close($contacts);
214 $data['next'] = DI::baseUrl() . $modulePath . $owner['nickname'] . '?page=' . ($page + 1);
217 $data['partOf'] = DI::baseUrl() . $modulePath . $owner['nickname'];
219 $data['orderedItems'] = $list;
226 * Public posts for the given owner
228 * @param array $owner Owner array
229 * @param integer $page Page number
230 * @param string $requester URL of requesting account
232 * @return array of posts
233 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
234 * @throws \ImagickException
236 public static function getOutbox($owner, $page = null, $requester = '')
238 $public_contact = Contact::getIdForURL($owner['url']);
239 $condition = ['uid' => 0, 'contact-id' => $public_contact,
240 'private' => [Item::PUBLIC, Item::UNLISTED]];
242 if (!empty($requester)) {
243 $requester_id = Contact::getIdForURL($requester, $owner['uid']);
244 if (!empty($requester_id)) {
245 $permissionSets = DI::permissionSet()->selectByContactId($requester_id, $owner['uid']);
246 if (!empty($permissionSets)) {
247 $condition = ['uid' => $owner['uid'], 'origin' => true,
248 'psid' => array_merge($permissionSets->column('id'),
249 [DI::permissionSet()->getIdFromACL($owner['uid'], '', '', '', '')])];
254 $condition = array_merge($condition,
255 ['author-id' => $public_contact,
256 'gravity' => [GRAVITY_PARENT, GRAVITY_COMMENT],
257 'deleted' => false, 'visible' => true]);
259 $count = Post::count($condition);
261 $data = ['@context' => ActivityPub::CONTEXT];
262 $data['id'] = DI::baseUrl() . '/outbox/' . $owner['nickname'];
263 $data['type'] = 'OrderedCollection';
264 $data['totalItems'] = $count;
267 $data['first'] = DI::baseUrl() . '/outbox/' . $owner['nickname'] . '?page=1';
269 $data['type'] = 'OrderedCollectionPage';
272 $condition['parent-network'] = Protocol::NATIVE_SUPPORT;
274 $items = Post::select(['id'], $condition, ['limit' => [($page - 1) * 20, 20], 'order' => ['created' => true]]);
275 while ($item = Post::fetch($items)) {
276 $activity = self::createActivityFromItem($item['id'], true);
277 $activity['type'] = $activity['type'] == 'Update' ? 'Create' : $activity['type'];
279 // Only list "Create" activity objects here, no reshares
280 if (!empty($activity['object']) && ($activity['type'] == 'Create')) {
281 $list[] = $activity['object'];
287 $data['next'] = DI::baseUrl() . '/outbox/' . $owner['nickname'] . '?page=' . ($page + 1);
290 $data['partOf'] = DI::baseUrl() . '/outbox/' . $owner['nickname'];
292 $data['orderedItems'] = $list;
299 * Return the service array containing information the used software and it's url
301 * @return array with service data
303 private static function getService()
305 return ['type' => 'Service',
306 'name' => FRIENDICA_PLATFORM . " '" . FRIENDICA_CODENAME . "' " . FRIENDICA_VERSION . '-' . DB_UPDATE_VERSION,
307 'url' => DI::baseUrl()->get()];
311 * Return the ActivityPub profile of the given user
313 * @param integer $uid User ID
314 * @return array with profile data
315 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
317 public static function getProfile($uid)
320 $condition = ['uid' => $uid, 'blocked' => false, 'account_expired' => false,
321 'account_removed' => false, 'verified' => true];
322 $fields = ['guid', 'nickname', 'pubkey', 'account-type', 'page-flags'];
323 $user = DBA::selectFirst('user', $fields, $condition);
324 if (!DBA::isResult($user)) {
328 $fields = ['locality', 'region', 'country-name'];
329 $profile = DBA::selectFirst('profile', $fields, ['uid' => $uid]);
330 if (!DBA::isResult($profile)) {
334 $fields = ['name', 'url', 'location', 'about', 'avatar', 'photo'];
335 $contact = DBA::selectFirst('contact', $fields, ['uid' => $uid, 'self' => true]);
336 if (!DBA::isResult($contact)) {
340 $contact = User::getSystemAccount();
341 $user = ['guid' => '', 'nickname' => $contact['nick'], 'pubkey' => $contact['pubkey'],
342 'account-type' => $contact['contact-type'], 'page-flags' => User::PAGE_FLAGS_NORMAL];
343 $profile = ['locality' => '', 'region' => '', 'country-name' => ''];
346 $data = ['@context' => ActivityPub::CONTEXT];
347 $data['id'] = $contact['url'];
349 if (!empty($user['guid'])) {
350 $data['diaspora:guid'] = $user['guid'];
353 $data['type'] = ActivityPub::ACCOUNT_TYPES[$user['account-type']];
356 $data['following'] = DI::baseUrl() . '/following/' . $user['nickname'];
357 $data['followers'] = DI::baseUrl() . '/followers/' . $user['nickname'];
358 $data['inbox'] = DI::baseUrl() . '/inbox/' . $user['nickname'];
359 $data['outbox'] = DI::baseUrl() . '/outbox/' . $user['nickname'];
361 $data['inbox'] = DI::baseUrl() . '/friendica/inbox';
364 $data['preferredUsername'] = $user['nickname'];
365 $data['name'] = $contact['name'];
367 if (!empty($profile['country-name'] . $profile['region'] . $profile['locality'])) {
368 $data['vcard:hasAddress'] = ['@type' => 'vcard:Home', 'vcard:country-name' => $profile['country-name'],
369 'vcard:region' => $profile['region'], 'vcard:locality' => $profile['locality']];
372 if (!empty($contact['about'])) {
373 $data['summary'] = BBCode::convert($contact['about'], false);
376 $data['url'] = $contact['url'];
377 $data['manuallyApprovesFollowers'] = in_array($user['page-flags'], [User::PAGE_FLAGS_NORMAL, User::PAGE_FLAGS_PRVGROUP]);
378 $data['publicKey'] = ['id' => $contact['url'] . '#main-key',
379 'owner' => $contact['url'],
380 'publicKeyPem' => $user['pubkey']];
381 $data['endpoints'] = ['sharedInbox' => DI::baseUrl() . '/inbox'];
382 $data['icon'] = ['type' => 'Image', 'url' => $contact['photo']];
384 $resourceid = Photo::ridFromURI($contact['photo']);
385 if (!empty($resourceid)) {
386 $photo = Photo::selectFirst(['type'], ["resource-id" => $resourceid]);
387 if (!empty($photo['type'])) {
388 $data['icon']['mediaType'] = $photo['type'];
392 if (!empty($contact['header'])) {
393 $data['image'] = ['type' => 'Image', 'url' => $contact['header']];
396 $data['generator'] = self::getService();
398 // tags: https://kitty.town/@inmysocks/100656097926961126.json
403 * @param string $username
405 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
407 public static function getDeletedUser($username)
410 '@context' => ActivityPub::CONTEXT,
411 'id' => DI::baseUrl() . '/profile/' . $username,
412 'type' => 'Tombstone',
413 'published' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
414 'updated' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
415 'deleted' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
420 * Returns an array with permissions of a given item array
424 * @return array with permissions
425 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
426 * @throws \ImagickException
428 private static function fetchPermissionBlockFromConversation($item)
430 if (empty($item['thr-parent'])) {
434 $condition = ['item-uri' => $item['thr-parent'], 'protocol' => Conversation::PARCEL_ACTIVITYPUB];
435 $conversation = DBA::selectFirst('conversation', ['source'], $condition);
436 if (!DBA::isResult($conversation)) {
440 $activity = json_decode($conversation['source'], true);
442 $actor = JsonLD::fetchElement($activity, 'actor', 'id');
443 if (!empty($actor)) {
444 $permissions['to'][] = $actor;
445 $profile = APContact::getByURL($actor);
450 $item_profile = APContact::getByURL($item['author-link']);
451 $exclude[] = $item['author-link'];
453 if ($item['gravity'] == GRAVITY_PARENT) {
454 $exclude[] = $item['owner-link'];
457 foreach (['to', 'cc', 'bto', 'bcc'] as $element) {
458 if (empty($activity[$element])) {
461 if (is_string($activity[$element])) {
462 $activity[$element] = [$activity[$element]];
465 foreach ($activity[$element] as $receiver) {
466 if (empty($receiver)) {
470 if (!empty($profile['followers']) && $receiver == $profile['followers'] && !empty($item_profile['followers'])) {
471 $permissions[$element][] = $item_profile['followers'];
472 } elseif (!in_array($receiver, $exclude)) {
473 $permissions[$element][] = $receiver;
481 * Check if the given item id is from ActivityPub
483 * @param integer $item_id
484 * @return boolean "true" if the post is from ActivityPub
486 private static function isAPPost(int $item_id)
488 if (empty($item_id)) {
492 return Post::exists(['id' => $item_id, 'network' => Protocol::ACTIVITYPUB]);
496 * Creates an array of permissions from an item thread
498 * @param array $item Item array
499 * @param boolean $blindcopy addressing via "bcc" or "cc"?
500 * @param integer $last_id Last item id for adding receivers
501 * @param boolean $forum_mode "true" means that we are sending content to a forum
503 * @return array with permission data
504 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
505 * @throws \ImagickException
507 private static function createPermissionBlockForItem($item, $blindcopy, $last_id = 0, $forum_mode = false)
510 $last_id = $item['id'];
515 // Check if we should always deliver our stuff via BCC
516 if (!empty($item['uid'])) {
517 $profile = User::getOwnerDataById($item['uid']);
518 if (!empty($profile)) {
519 $always_bcc = $profile['hide-friends'];
523 if (DI::config()->get('system', 'ap_always_bcc')) {
527 if (self::isAnnounce($item) || DI::config()->get('debug', 'total_ap_delivery') || self::isAPPost($last_id)) {
528 // Will be activated in a later step
529 $networks = Protocol::FEDERATED;
531 // For now only send to these contacts:
532 $networks = [Protocol::ACTIVITYPUB, Protocol::OSTATUS];
535 $data = ['to' => [], 'cc' => [], 'bcc' => []];
537 if ($item['gravity'] == GRAVITY_PARENT) {
538 $actor_profile = APContact::getByURL($item['owner-link']);
540 $actor_profile = APContact::getByURL($item['author-link']);
545 $terms = Tag::getByURIId($item['uri-id'], [Tag::MENTION, Tag::IMPLICIT_MENTION, Tag::EXCLUSIVE_MENTION]);
547 if ($item['private'] != Item::PRIVATE) {
548 // Directly mention the original author upon a quoted reshare.
549 // Else just ensure that the original author receives the reshare.
550 $announce = self::getAnnounceArray($item);
551 if (!empty($announce['comment'])) {
552 $data['to'][] = $announce['actor']['url'];
553 } elseif (!empty($announce)) {
554 $data['cc'][] = $announce['actor']['url'];
557 $data = array_merge($data, self::fetchPermissionBlockFromConversation($item));
559 // Check if the item is completely public or unlisted
560 if ($item['private'] == Item::PUBLIC) {
561 $data['to'][] = ActivityPub::PUBLIC_COLLECTION;
563 $data['cc'][] = ActivityPub::PUBLIC_COLLECTION;
566 foreach ($terms as $term) {
567 $profile = APContact::getByURL($term['url'], false);
568 if (!empty($profile)) {
569 if ($term['type'] == Tag::EXCLUSIVE_MENTION) {
571 if (!empty($profile['followers']) && ($profile['type'] == 'Group')) {
572 $data['cc'][] = $profile['followers'];
575 $data['to'][] = $profile['url'];
579 $receiver_list = Item::enumeratePermissions($item, true);
581 foreach ($terms as $term) {
582 $cid = Contact::getIdForURL($term['url'], $item['uid']);
583 if (!empty($cid) && in_array($cid, $receiver_list)) {
584 $contact = DBA::selectFirst('contact', ['url', 'network', 'protocol', 'gsid'], ['id' => $cid, 'network' => Protocol::FEDERATED]);
585 if (!DBA::isResult($contact) || !self::isAPContact($contact, $networks)) {
589 if (!empty($profile = APContact::getByURL($contact['url'], false))) {
590 $data['to'][] = $profile['url'];
595 foreach ($receiver_list as $receiver) {
596 $contact = DBA::selectFirst('contact', ['url', 'hidden', 'network', 'protocol', 'gsid'], ['id' => $receiver, 'network' => Protocol::FEDERATED]);
597 if (!DBA::isResult($contact) || !self::isAPContact($contact, $networks)) {
601 if (!empty($profile = APContact::getByURL($contact['url'], false))) {
602 if ($contact['hidden'] || $always_bcc) {
603 $data['bcc'][] = $profile['url'];
605 $data['cc'][] = $profile['url'];
611 if (!empty($item['parent'])) {
612 $parents = Post::select(['id', 'author-link', 'owner-link', 'gravity', 'uri'], ['parent' => $item['parent']]);
613 while ($parent = Post::fetch($parents)) {
614 if ($parent['gravity'] == GRAVITY_PARENT) {
615 $profile = APContact::getByURL($parent['owner-link'], false);
616 if (!empty($profile)) {
617 if ($item['gravity'] != GRAVITY_PARENT) {
618 // Comments to forums are directed to the forum
619 // But comments to forums aren't directed to the followers collection
620 // This rule is only valid when the actor isn't the forum.
621 // The forum needs to transmit their content to their followers.
622 if (($profile['type'] == 'Group') && ($profile['url'] != ($actor_profile['url'] ?? ''))) {
623 $data['to'][] = $profile['url'];
625 $data['cc'][] = $profile['url'];
626 if (($item['private'] != Item::PRIVATE) && !empty($actor_profile['followers'])) {
627 $data['cc'][] = $actor_profile['followers'];
630 } elseif (!$exclusive) {
631 // Public thread parent post always are directed to the followers.
632 // This mustn't be done by posts that are directed to forum servers via the exclusive mention.
633 // But possibly in that case we could add the "followers" collection of the forum to the message.
634 if (($item['private'] != Item::PRIVATE) && !$forum_mode) {
635 $data['cc'][] = $actor_profile['followers'];
641 // Don't include data from future posts
642 if ($parent['id'] >= $last_id) {
646 $profile = APContact::getByURL($parent['author-link'], false);
647 if (!empty($profile)) {
648 if (($profile['type'] == 'Group') || ($parent['uri'] == $item['thr-parent'])) {
649 $data['to'][] = $profile['url'];
651 $data['cc'][] = $profile['url'];
655 DBA::close($parents);
658 $data['to'] = array_unique($data['to']);
659 $data['cc'] = array_unique($data['cc']);
660 $data['bcc'] = array_unique($data['bcc']);
662 if (($key = array_search($item['author-link'], $data['to'])) !== false) {
663 unset($data['to'][$key]);
666 if (($key = array_search($item['author-link'], $data['cc'])) !== false) {
667 unset($data['cc'][$key]);
670 if (($key = array_search($item['author-link'], $data['bcc'])) !== false) {
671 unset($data['bcc'][$key]);
674 foreach ($data['to'] as $to) {
675 if (($key = array_search($to, $data['cc'])) !== false) {
676 unset($data['cc'][$key]);
679 if (($key = array_search($to, $data['bcc'])) !== false) {
680 unset($data['bcc'][$key]);
684 foreach ($data['cc'] as $cc) {
685 if (($key = array_search($cc, $data['bcc'])) !== false) {
686 unset($data['bcc'][$key]);
690 $receivers = ['to' => array_values($data['to']), 'cc' => array_values($data['cc']), 'bcc' => array_values($data['bcc'])];
693 unset($receivers['bcc']);
700 * Check if an inbox is archived
702 * @param string $url Inbox url
704 * @return boolean "true" if inbox is archived
706 public static function archivedInbox($url)
708 return DBA::exists('inbox-status', ['url' => $url, 'archive' => true]);
712 * Check if a given contact should be delivered via AP
714 * @param array $contact
715 * @param array $networks
719 private static function isAPContact(array $contact, array $networks)
721 if (in_array($contact['network'], $networks) || ($contact['protocol'] == Protocol::ACTIVITYPUB)) {
725 return GServer::getProtocol($contact['gsid'] ?? 0) == Post\DeliveryData::ACTIVITYPUB;
729 * Fetches a list of inboxes of followers of a given user
731 * @param integer $uid User ID
732 * @param boolean $personal fetch personal inboxes
733 * @param boolean $all_ap Retrieve all AP enabled inboxes
735 * @return array of follower inboxes
736 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
737 * @throws \ImagickException
739 public static function fetchTargetInboxesforUser($uid, $personal = false, bool $all_ap = false)
745 if (!empty($item['uid'])) {
746 $profile = User::getOwnerDataById($item['uid']);
747 if (!empty($profile)) {
748 $isforum = $profile['account-type'] == User::ACCOUNT_TYPE_COMMUNITY;
752 if (DI::config()->get('debug', 'total_ap_delivery') || $all_ap) {
753 // Will be activated in a later step
754 $networks = Protocol::FEDERATED;
756 // For now only send to these contacts:
757 $networks = [Protocol::ACTIVITYPUB, Protocol::OSTATUS];
760 $condition = ['uid' => $uid, 'archive' => false, 'pending' => false, 'blocked' => false, 'network' => Protocol::FEDERATED];
763 $condition['rel'] = [Contact::FOLLOWER, Contact::FRIEND];
766 $contacts = DBA::select('contact', ['id', 'url', 'network', 'protocol', 'gsid'], $condition);
767 while ($contact = DBA::fetch($contacts)) {
768 if (!self::isAPContact($contact, $networks)) {
772 if ($isforum && ($contact['network'] == Protocol::DFRN)) {
776 if (Network::isUrlBlocked($contact['url'])) {
780 $profile = APContact::getByURL($contact['url'], false);
781 if (!empty($profile)) {
782 if (empty($profile['sharedinbox']) || $personal || Contact::isLocal($contact['url'])) {
783 $target = $profile['inbox'];
785 $target = $profile['sharedinbox'];
787 if (!self::archivedInbox($target)) {
788 $inboxes[$target][] = $contact['id'];
792 DBA::close($contacts);
798 * Fetches an array of inboxes for the given item and user
800 * @param array $item Item array
801 * @param integer $uid User ID
802 * @param boolean $personal fetch personal inboxes
803 * @param integer $last_id Last item id for adding receivers
804 * @param boolean $forum_mode "true" means that we are sending content to a forum
805 * @return array with inboxes
806 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
807 * @throws \ImagickException
809 public static function fetchTargetInboxes($item, $uid, $personal = false, $last_id = 0, $forum_mode = false)
811 $permissions = self::createPermissionBlockForItem($item, true, $last_id, $forum_mode);
812 if (empty($permissions)) {
818 if ($item['gravity'] == GRAVITY_ACTIVITY) {
819 $item_profile = APContact::getByURL($item['author-link'], false);
821 $item_profile = APContact::getByURL($item['owner-link'], false);
824 if (empty($item_profile)) {
828 $profile_uid = User::getIdForURL($item_profile['url']);
830 foreach (['to', 'cc', 'bto', 'bcc'] as $element) {
831 if (empty($permissions[$element])) {
835 $blindcopy = in_array($element, ['bto', 'bcc']);
837 foreach ($permissions[$element] as $receiver) {
838 if (empty($receiver) || Network::isUrlBlocked($receiver)) {
842 if ($item_profile && ($receiver == $item_profile['followers']) && ($uid == $profile_uid)) {
843 $inboxes = array_merge($inboxes, self::fetchTargetInboxesforUser($uid, $personal, self::isAPPost($last_id)));
845 $profile = APContact::getByURL($receiver, false);
846 if (!empty($profile)) {
847 $contact = Contact::getByURLForUser($receiver, $uid, false, ['id']);
849 if (empty($profile['sharedinbox']) || $personal || $blindcopy || Contact::isLocal($receiver)) {
850 $target = $profile['inbox'];
852 $target = $profile['sharedinbox'];
854 if (!self::archivedInbox($target)) {
855 $inboxes[$target][] = $contact['id'] ?? 0;
866 * Creates an array in the structure of the item table for a given mail id
868 * @param integer $mail_id
873 public static function ItemArrayFromMail($mail_id, $use_title = false)
875 $mail = DBA::selectFirst('mail', [], ['id' => $mail_id]);
876 if (!DBA::isResult($mail)) {
880 $reply = DBA::selectFirst('mail', ['uri', 'uri-id', 'from-url'], ['parent-uri' => $mail['parent-uri'], 'reply' => false]);
882 // Making the post more compatible for Mastodon by:
883 // - Making it a note and not an article (no title)
884 // - Moving the title into the "summary" field that is used as a "content warning"
887 $mail['body'] = '[abstract]' . $mail['title'] . "[/abstract]\n" . $mail['body'];
891 $mail['author-link'] = $mail['owner-link'] = $mail['from-url'];
892 $mail['owner-id'] = $mail['author-id'];
893 $mail['allow_cid'] = '<'.$mail['contact-id'].'>';
894 $mail['allow_gid'] = '';
895 $mail['deny_cid'] = '';
896 $mail['deny_gid'] = '';
897 $mail['private'] = Item::PRIVATE;
898 $mail['deleted'] = false;
899 $mail['edited'] = $mail['created'];
900 $mail['plink'] = DI::baseUrl() . '/message/' . $mail['id'];
901 $mail['parent-uri'] = $reply['uri'];
902 $mail['parent-uri-id'] = $reply['uri-id'];
903 $mail['parent-author-id'] = Contact::getIdForURL($reply['from-url'], 0, false);
904 $mail['gravity'] = ($mail['reply'] ? GRAVITY_COMMENT: GRAVITY_PARENT);
905 $mail['event-type'] = '';
906 $mail['language'] = '';
913 * Creates an activity array for a given mail id
915 * @param integer $mail_id
916 * @param boolean $object_mode Is the activity item is used inside another object?
918 * @return array of activity
921 public static function createActivityFromMail($mail_id, $object_mode = false)
923 $mail = self::ItemArrayFromMail($mail_id);
927 $object = self::createNote($mail);
930 $data = ['@context' => ActivityPub::CONTEXT];
935 $data['id'] = $mail['uri'] . '/Create';
936 $data['type'] = 'Create';
937 $data['actor'] = $mail['author-link'];
938 $data['published'] = DateTimeFormat::utc($mail['created'] . '+00:00', DateTimeFormat::ATOM);
939 $data['instrument'] = self::getService();
940 $data = array_merge($data, self::createPermissionBlockForItem($mail, true));
942 if (empty($data['to']) && !empty($data['cc'])) {
943 $data['to'] = $data['cc'];
946 if (empty($data['to']) && !empty($data['bcc'])) {
947 $data['to'] = $data['bcc'];
953 $object['to'] = $data['to'];
954 $object['tag'] = [['type' => 'Mention', 'href' => $object['to'][0], 'name' => '']];
956 unset($object['cc']);
957 unset($object['bcc']);
959 $data['directMessage'] = true;
961 $data['object'] = $object;
963 $owner = User::getOwnerDataById($mail['uid']);
965 if (!$object_mode && !empty($owner)) {
966 return LDSignature::sign($data, $owner);
973 * Returns the activity type of a given item
977 * @return string with activity type
978 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
979 * @throws \ImagickException
981 private static function getTypeOfItem($item)
985 // Only check for a reshare, if it is a real reshare and no quoted reshare
986 if (strpos($item['body'], "[share") === 0) {
987 $announce = self::getAnnounceArray($item);
988 $reshared = !empty($announce);
993 } elseif ($item['verb'] == Activity::POST) {
994 if ($item['created'] == $item['edited']) {
999 } elseif ($item['verb'] == Activity::LIKE) {
1001 } elseif ($item['verb'] == Activity::DISLIKE) {
1003 } elseif ($item['verb'] == Activity::ATTEND) {
1005 } elseif ($item['verb'] == Activity::ATTENDNO) {
1007 } elseif ($item['verb'] == Activity::ATTENDMAYBE) {
1008 $type = 'TentativeAccept';
1009 } elseif ($item['verb'] == Activity::FOLLOW) {
1011 } elseif ($item['verb'] == Activity::TAG) {
1013 } elseif ($item['verb'] == Activity::ANNOUNCE) {
1023 * Creates the activity or fetches it from the cache
1025 * @param integer $item_id
1026 * @param boolean $force Force new cache entry
1028 * @return array with the activity
1029 * @throws \Exception
1031 public static function createCachedActivityFromItem($item_id, $force = false)
1033 $cachekey = 'APDelivery:createActivity:' . $item_id;
1036 $data = DI::cache()->get($cachekey);
1037 if (!is_null($data)) {
1042 $data = self::createActivityFromItem($item_id);
1044 DI::cache()->set($cachekey, $data, Duration::QUARTER_HOUR);
1049 * Creates an activity array for a given item id
1051 * @param integer $item_id
1052 * @param boolean $object_mode Is the activity item is used inside another object?
1054 * @return false|array
1055 * @throws \Exception
1057 public static function createActivityFromItem(int $item_id, bool $object_mode = false)
1059 Logger::info('Fetching activity', ['item' => $item_id]);
1060 $item = Post::selectFirst(Item::DELIVER_FIELDLIST, ['id' => $item_id, 'parent-network' => Protocol::NATIVE_SUPPORT]);
1061 if (!DBA::isResult($item)) {
1065 // In case of a forum post ensure to return the original post if author and forum are on the same machine
1066 if (($item['gravity'] == GRAVITY_PARENT) && !empty($item['forum_mode'])) {
1067 $author = Contact::getById($item['author-id'], ['nurl']);
1068 if (!empty($author['nurl'])) {
1069 $self = Contact::selectFirst(['uid'], ['nurl' => $author['nurl'], 'self' => true]);
1070 if (!empty($self['uid'])) {
1071 $forum_item = Post::selectFirst(Item::DELIVER_FIELDLIST, ['uri-id' => $item['uri-id'], 'uid' => $self['uid']]);
1072 if (DBA::isResult($forum_item)) {
1073 $item = $forum_item;
1079 if (empty($item['uri-id'])) {
1080 Logger::warning('Item without uri-id', ['item' => $item]);
1084 if (!$item['deleted']) {
1085 $condition = ['item-uri' => $item['uri'], 'protocol' => Conversation::PARCEL_ACTIVITYPUB];
1086 $conversation = DBA::selectFirst('conversation', ['source'], $condition);
1087 if (!$item['origin'] && DBA::isResult($conversation)) {
1088 $data = json_decode($conversation['source'], true);
1089 if (!empty($data['type'])) {
1090 if (in_array($data['type'], ['Create', 'Update'])) {
1092 unset($data['@context']);
1093 unset($data['signature']);
1095 Logger::info('Return stored conversation', ['item' => $item_id]);
1097 } elseif (in_array('as:' . $data['type'], Receiver::CONTENT_TYPES)) {
1098 if (!empty($data['@context'])) {
1099 $context = $data['@context'];
1100 unset($data['@context']);
1102 unset($data['actor']);
1109 $type = self::getTypeOfItem($item);
1111 if (!$object_mode) {
1112 $data = ['@context' => $context ?? ActivityPub::CONTEXT];
1114 if ($item['deleted'] && ($item['gravity'] == GRAVITY_ACTIVITY)) {
1116 } elseif ($item['deleted']) {
1123 if ($type == 'Delete') {
1124 $data['id'] = Item::newURI($item['uid'], $item['guid']) . '/' . $type;;
1125 } elseif (($item['gravity'] == GRAVITY_ACTIVITY) && ($type != 'Undo')) {
1126 $data['id'] = $item['uri'];
1128 $data['id'] = $item['uri'] . '/' . $type;
1131 $data['type'] = $type;
1133 if (($type != 'Announce') || ($item['gravity'] != GRAVITY_PARENT)) {
1134 $data['actor'] = $item['author-link'];
1136 $data['actor'] = $item['owner-link'];
1139 $data['published'] = DateTimeFormat::utc($item['created'] . '+00:00', DateTimeFormat::ATOM);
1141 $data['instrument'] = self::getService();
1143 $data = array_merge($data, self::createPermissionBlockForItem($item, false));
1145 if (in_array($data['type'], ['Create', 'Update', 'Delete'])) {
1146 $data['object'] = $object ?? self::createNote($item);
1147 } elseif ($data['type'] == 'Add') {
1148 $data = self::createAddTag($item, $data);
1149 } elseif ($data['type'] == 'Announce') {
1150 if ($item['verb'] == ACTIVITY::ANNOUNCE) {
1151 $data['object'] = $item['thr-parent'];
1153 $data = self::createAnnounce($item, $data);
1155 } elseif ($data['type'] == 'Follow') {
1156 $data['object'] = $item['parent-uri'];
1157 } elseif ($data['type'] == 'Undo') {
1158 $data['object'] = self::createActivityFromItem($item_id, true);
1160 $data['diaspora:guid'] = $item['guid'];
1161 if (!empty($item['signed_text'])) {
1162 $data['diaspora:like'] = $item['signed_text'];
1164 $data['object'] = $item['thr-parent'];
1167 if (!empty($item['contact-uid'])) {
1168 $uid = $item['contact-uid'];
1170 $uid = $item['uid'];
1173 $owner = User::getOwnerDataById($uid);
1175 Logger::info('Fetched activity', ['item' => $item_id, 'uid' => $uid]);
1177 // We don't sign if we aren't the actor. This is important for relaying content especially for forums
1178 if (!$object_mode && !empty($owner) && ($data['actor'] == $owner['url'])) {
1179 return LDSignature::sign($data, $owner);
1184 /// @todo Create "conversation" entry
1188 * Creates a location entry for a given item array
1190 * @param array $item
1192 * @return array with location array
1194 private static function createLocation($item)
1196 $location = ['type' => 'Place'];
1198 if (!empty($item['location'])) {
1199 $location['name'] = $item['location'];
1204 if (empty($item['coord'])) {
1205 $coord = Map::getCoordinates($item['location']);
1207 $coords = explode(' ', $item['coord']);
1208 if (count($coords) == 2) {
1209 $coord = ['lat' => $coords[0], 'lon' => $coords[1]];
1213 if (!empty($coord['lat']) && !empty($coord['lon'])) {
1214 $location['latitude'] = $coord['lat'];
1215 $location['longitude'] = $coord['lon'];
1222 * Returns a tag array for a given item array
1224 * @param array $item
1226 * @return array of tags
1227 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1229 private static function createTagList($item)
1233 $terms = Tag::getByURIId($item['uri-id'], [Tag::HASHTAG, Tag::MENTION, Tag::IMPLICIT_MENTION, Tag::EXCLUSIVE_MENTION]);
1234 foreach ($terms as $term) {
1235 if ($term['type'] == Tag::HASHTAG) {
1236 $url = DI::baseUrl() . '/search?tag=' . urlencode($term['name']);
1237 $tags[] = ['type' => 'Hashtag', 'href' => $url, 'name' => '#' . $term['name']];
1239 $contact = Contact::getByURL($term['url'], false, ['addr']);
1240 if (empty($contact)) {
1243 if (!empty($contact['addr'])) {
1244 $mention = '@' . $contact['addr'];
1246 $mention = '@' . $term['url'];
1249 $tags[] = ['type' => 'Mention', 'href' => $term['url'], 'name' => $mention];
1253 $announce = self::getAnnounceArray($item);
1254 // Mention the original author upon commented reshares
1255 if (!empty($announce['comment'])) {
1256 $tags[] = ['type' => 'Mention', 'href' => $announce['actor']['url'], 'name' => '@' . $announce['actor']['addr']];
1263 * Adds attachment data to the JSON document
1265 * @param array $item Data of the item that is to be posted
1266 * @param string $type Object type
1268 * @return array with attachment data
1269 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1271 private static function createAttachmentList($item, $type)
1275 $uriids = [$item['uri-id']];
1276 $shared = BBCode::fetchShareAttributes($item['body']);
1277 if (!empty($shared['guid'])) {
1278 $shared_item = Post::selectFirst(['uri-id'], ['guid' => $shared['guid']]);
1279 if (!empty($shared_item['uri-id'])) {
1280 $uriids[] = $shared_item['uri-id'];
1285 foreach ($uriids as $uriid) {
1286 foreach (Post\Media::getByURIId($uriid, [Post\Media::DOCUMENT, Post\Media::TORRENT]) as $attachment) {
1287 if (in_array($attachment['url'], $urls)) {
1290 $urls[] = $attachment['url'];
1292 $attachments[] = ['type' => 'Document',
1293 'mediaType' => $attachment['mimetype'],
1294 'url' => $attachment['url'],
1295 'name' => $attachment['description']];
1299 if ($type != 'Note') {
1300 return $attachments;
1303 foreach ($uriids as $uriid) {
1304 foreach (Post\Media::getByURIId($uriid, [Post\Media::AUDIO, Post\Media::IMAGE, Post\Media::VIDEO]) as $attachment) {
1305 if (in_array($attachment['url'], $urls)) {
1308 $urls[] = $attachment['url'];
1310 $attachments[] = ['type' => 'Document',
1311 'mediaType' => $attachment['mimetype'],
1312 'url' => $attachment['url'],
1313 'name' => $attachment['description']];
1315 // Currently deactivated, since it creates side effects on Mastodon and Pleroma.
1316 // It will be activated, once this cleared.
1318 foreach (Post\Media::getByURIId($uriid, [Post\Media::HTML]) as $attachment) {
1319 if (in_array($attachment['url'], $urls)) {
1322 $urls[] = $attachment['url'];
1324 $attachments[] = ['type' => 'Page',
1325 'mediaType' => $attachment['mimetype'],
1326 'url' => $attachment['url'],
1327 'name' => $attachment['description']];
1331 return $attachments;
1335 * Callback function to replace a Friendica style mention in a mention that is used on AP
1337 * @param array $match Matching values for the callback
1338 * @return string Replaced mention
1339 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1341 private static function mentionCallback($match)
1343 if (empty($match[1])) {
1347 $data = Contact::getByURL($match[1], false, ['url', 'alias', 'nick']);
1348 if (empty($data['nick'])) {
1352 return '[url=' . $data['url'] . ']@' . $data['nick'] . '[/url]';
1356 * Callback function to replace a Friendica style mention in a mention for a summary
1358 * @param array $match Matching values for the callback
1359 * @return string Replaced mention
1360 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1362 private static function mentionAddrCallback($match)
1364 if (empty($match[1])) {
1368 $data = Contact::getByURL($match[1], false, ['addr']);
1369 if (empty($data['addr'])) {
1373 return '@' . $data['addr'];
1377 * Remove image elements since they are added as attachment
1379 * @param string $body
1381 * @return string with removed images
1383 private static function removePictures($body)
1385 // Simplify image codes
1386 $body = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '[img]$3[/img]', $body);
1387 $body = preg_replace("/\[img\=(.*?)\](.*?)\[\/img\]/ism", '[img]$1[/img]', $body);
1389 // Now remove local links
1390 $body = preg_replace_callback(
1391 '/\[url=([^\[\]]*)\]\[img\](.*)\[\/img\]\[\/url\]/Usi',
1393 // We remove the link when it is a link to a local photo page
1394 if (Photo::isLocalPage($match[1])) {
1397 // otherwise we just return the link
1398 return '[url]' . $match[1] . '[/url]';
1403 // Remove all pictures
1404 $body = preg_replace("/\[img\]([^\[\]]*)\[\/img\]/Usi", '', $body);
1410 * Fetches the "context" value for a givem item array from the "conversation" table
1412 * @param array $item
1414 * @return string with context url
1415 * @throws \Exception
1417 private static function fetchContextURLForItem($item)
1419 $conversation = DBA::selectFirst('conversation', ['conversation-href', 'conversation-uri'], ['item-uri' => $item['parent-uri']]);
1420 if (DBA::isResult($conversation) && !empty($conversation['conversation-href'])) {
1421 $context_uri = $conversation['conversation-href'];
1422 } elseif (DBA::isResult($conversation) && !empty($conversation['conversation-uri'])) {
1423 $context_uri = $conversation['conversation-uri'];
1425 $context_uri = $item['parent-uri'] . '#context';
1427 return $context_uri;
1431 * Returns if the post contains sensitive content ("nsfw")
1433 * @param integer $uri_id
1436 * @throws \Exception
1438 private static function isSensitive($uri_id)
1440 return DBA::exists('tag-view', ['uri-id' => $uri_id, 'name' => 'nsfw']);
1444 * Creates event data
1446 * @param array $item
1448 * @return array with the event data
1449 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1451 private static function createEvent($item)
1454 $event['name'] = $item['event-summary'];
1455 $event['content'] = BBCode::convert($item['event-desc'], false, BBCode::ACTIVITYPUB);
1456 $event['startTime'] = DateTimeFormat::utc($item['event-start'] . '+00:00', DateTimeFormat::ATOM);
1458 if (!$item['event-nofinish']) {
1459 $event['endTime'] = DateTimeFormat::utc($item['event-finish'] . '+00:00', DateTimeFormat::ATOM);
1462 if (!empty($item['event-location'])) {
1463 $item['location'] = $item['event-location'];
1464 $event['location'] = self::createLocation($item);
1467 $event['dfrn:adjust'] = (bool)$item['event-adjust'];
1473 * Creates a note/article object array
1475 * @param array $item
1477 * @return array with the object data
1478 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1479 * @throws \ImagickException
1481 public static function createNote($item)
1487 if ($item['event-type'] == 'event') {
1489 } elseif (!empty($item['title'])) {
1495 if ($item['deleted']) {
1496 $type = 'Tombstone';
1500 $data['id'] = $item['uri'];
1501 $data['type'] = $type;
1503 if ($item['deleted']) {
1507 $data['summary'] = BBCode::toPlaintext(BBCode::getAbstract($item['body'], Protocol::ACTIVITYPUB));
1509 if ($item['uri'] != $item['thr-parent']) {
1510 $data['inReplyTo'] = $item['thr-parent'];
1512 $data['inReplyTo'] = null;
1515 $data['diaspora:guid'] = $item['guid'];
1516 $data['published'] = DateTimeFormat::utc($item['created'] . '+00:00', DateTimeFormat::ATOM);
1518 if ($item['created'] != $item['edited']) {
1519 $data['updated'] = DateTimeFormat::utc($item['edited'] . '+00:00', DateTimeFormat::ATOM);
1522 $data['url'] = $item['plink'];
1523 $data['attributedTo'] = $item['author-link'];
1524 $data['sensitive'] = self::isSensitive($item['uri-id']);
1525 $data['context'] = self::fetchContextURLForItem($item);
1527 if (!empty($item['title'])) {
1528 $data['name'] = BBCode::toPlaintext($item['title'], false);
1531 $permission_block = self::createPermissionBlockForItem($item, false);
1533 $body = $item['body'];
1535 if ($type == 'Note') {
1536 $body = $item['raw-body'] ?? self::removePictures($body);
1540 * @todo Improve the automated summary
1541 * This part is currently deactivated. The automated summary seems to be more
1542 * confusing than helping. But possibly we will find a better way.
1543 * So the code is left here for now as a reminder
1545 * } elseif (($type == 'Article') && empty($data['summary'])) {
1546 * $regexp = "/[@!]\[url\=([^\[\]]*)\].*?\[\/url\]/ism";
1547 * $summary = preg_replace_callback($regexp, ['self', 'mentionAddrCallback'], $body);
1548 * $data['summary'] = BBCode::toPlaintext(Plaintext::shorten(self::removePictures($summary), 1000));
1552 if (empty($item['uid']) || !Feature::isEnabled($item['uid'], 'explicit_mentions')) {
1553 $body = self::prependMentions($body, $item['uri-id'], $item['author-link']);
1556 if ($type == 'Event') {
1557 $data = array_merge($data, self::createEvent($item));
1559 $regexp = "/[@!]\[url\=([^\[\]]*)\].*?\[\/url\]/ism";
1560 $body = preg_replace_callback($regexp, ['self', 'mentionCallback'], $body);
1562 $data['content'] = BBCode::convert($body, false, BBCode::ACTIVITYPUB);
1565 // The regular "content" field does contain a minimized HTML. This is done since systems like
1566 // Mastodon has got problems with - for example - embedded pictures.
1567 // The contentMap does contain the unmodified HTML.
1568 $language = self::getLanguage($item);
1569 if (!empty($language)) {
1570 $regexp = "/[@!]\[url\=([^\[\]]*)\].*?\[\/url\]/ism";
1571 $richbody = preg_replace_callback($regexp, ['self', 'mentionCallback'], $item['body']);
1572 $richbody = BBCode::removeAttachment($richbody);
1574 $data['contentMap'][$language] = BBCode::convert($richbody, false, BBCode::EXTERNAL);
1577 $data['source'] = ['content' => $item['body'], 'mediaType' => "text/bbcode"];
1579 if (!empty($item['signed_text']) && ($item['uri'] != $item['thr-parent'])) {
1580 $data['diaspora:comment'] = $item['signed_text'];
1583 $data['attachment'] = self::createAttachmentList($item, $type);
1584 $data['tag'] = self::createTagList($item);
1586 if (empty($data['location']) && (!empty($item['coord']) || !empty($item['location']))) {
1587 $data['location'] = self::createLocation($item);
1590 if (!empty($item['app'])) {
1591 $data['generator'] = ['type' => 'Application', 'name' => $item['app']];
1594 $data = array_merge($data, $permission_block);
1600 * Fetches the language from the post, the user or the system.
1602 * @param array $item
1604 * @return string language string
1606 private static function getLanguage(array $item)
1608 // Try to fetch the language from the post itself
1609 if (!empty($item['language'])) {
1610 $languages = array_keys(json_decode($item['language'], true));
1611 if (!empty($languages[0])) {
1612 return $languages[0];
1616 // Otherwise use the user's language
1617 if (!empty($item['uid'])) {
1618 $user = DBA::selectFirst('user', ['language'], ['uid' => $item['uid']]);
1619 if (!empty($user['language'])) {
1620 return $user['language'];
1624 // And finally just use the system language
1625 return DI::config()->get('system', 'language');
1629 * Creates an an "add tag" entry
1631 * @param array $item
1632 * @param array $data activity data
1634 * @return array with activity data for adding tags
1635 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1636 * @throws \ImagickException
1638 private static function createAddTag($item, $data)
1640 $object = XML::parseString($item['object']);
1641 $target = XML::parseString($item["target"]);
1643 $data['diaspora:guid'] = $item['guid'];
1644 $data['actor'] = $item['author-link'];
1645 $data['target'] = (string)$target->id;
1646 $data['summary'] = BBCode::toPlaintext($item['body']);
1647 $data['object'] = ['id' => (string)$object->id, 'type' => 'tag', 'name' => (string)$object->title, 'content' => (string)$object->content];
1653 * Creates an announce object entry
1655 * @param array $item
1656 * @param array $data activity data
1658 * @return array with activity data
1659 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1660 * @throws \ImagickException
1662 private static function createAnnounce($item, $data)
1664 $orig_body = $item['body'];
1665 $announce = self::getAnnounceArray($item);
1666 if (empty($announce)) {
1667 $data['type'] = 'Create';
1668 $data['object'] = self::createNote($item);
1672 if (empty($announce['comment'])) {
1673 // Pure announce, without a quote
1674 $data['type'] = 'Announce';
1675 $data['object'] = $announce['object']['uri'];
1680 $data['type'] = 'Create';
1681 $item['body'] = $announce['comment'] . "\n" . $announce['object']['plink'];
1682 $data['object'] = self::createNote($item);
1684 /// @todo Finally descide how to implement this in AP. This is a possible way:
1685 $data['object']['attachment'][] = self::createNote($announce['object']);
1687 $data['object']['source']['content'] = $orig_body;
1692 * Return announce related data if the item is an annunce
1694 * @param array $item
1698 public static function getAnnounceArray($item)
1700 $reshared = Item::getShareArray($item);
1701 if (empty($reshared['guid'])) {
1705 $reshared_item = Post::selectFirst(Item::DELIVER_FIELDLIST, ['guid' => $reshared['guid']]);
1706 if (!DBA::isResult($reshared_item)) {
1710 if (!in_array($reshared_item['network'], [Protocol::ACTIVITYPUB, Protocol::DFRN])) {
1714 $profile = APContact::getByURL($reshared_item['author-link'], false);
1715 if (empty($profile)) {
1719 return ['object' => $reshared_item, 'actor' => $profile, 'comment' => $reshared['comment']];
1723 * Checks if the provided item array is an announce
1725 * @param array $item
1729 public static function isAnnounce($item)
1731 if (!empty($item['verb']) && ($item['verb'] == Activity::ANNOUNCE)) {
1735 $announce = self::getAnnounceArray($item);
1736 if (empty($announce)) {
1740 return empty($announce['comment']);
1744 * Creates an activity id for a given contact id
1746 * @param integer $cid Contact ID of target
1748 * @return bool|string activity id
1750 public static function activityIDFromContact($cid)
1752 $contact = DBA::selectFirst('contact', ['uid', 'id', 'created'], ['id' => $cid]);
1753 if (!DBA::isResult($contact)) {
1757 $hash = hash('ripemd128', $contact['uid'].'-'.$contact['id'].'-'.$contact['created']);
1758 $uuid = substr($hash, 0, 8). '-' . substr($hash, 8, 4) . '-' . substr($hash, 12, 4) . '-' . substr($hash, 16, 4) . '-' . substr($hash, 20, 12);
1759 return DI::baseUrl() . '/activity/' . $uuid;
1763 * Transmits a contact suggestion to a given inbox
1765 * @param integer $uid User ID
1766 * @param string $inbox Target inbox
1767 * @param integer $suggestion_id Suggestion ID
1769 * @return boolean was the transmission successful?
1770 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1772 public static function sendContactSuggestion($uid, $inbox, $suggestion_id)
1774 $owner = User::getOwnerDataById($uid);
1776 $suggestion = DI::fsuggest()->getById($suggestion_id);
1778 $data = ['@context' => ActivityPub::CONTEXT,
1779 'id' => DI::baseUrl() . '/activity/' . System::createGUID(),
1780 'type' => 'Announce',
1781 'actor' => $owner['url'],
1782 'object' => $suggestion->url,
1783 'content' => $suggestion->note,
1784 'instrument' => self::getService(),
1785 'to' => [ActivityPub::PUBLIC_COLLECTION],
1788 $signed = LDSignature::sign($data, $owner);
1790 Logger::log('Deliver profile deletion for user ' . $uid . ' to ' . $inbox . ' via ActivityPub', Logger::DEBUG);
1791 return HTTPSignature::transmit($signed, $inbox, $uid);
1795 * Transmits a profile relocation to a given inbox
1797 * @param integer $uid User ID
1798 * @param string $inbox Target inbox
1800 * @return boolean was the transmission successful?
1801 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1803 public static function sendProfileRelocation($uid, $inbox)
1805 $owner = User::getOwnerDataById($uid);
1807 $data = ['@context' => ActivityPub::CONTEXT,
1808 'id' => DI::baseUrl() . '/activity/' . System::createGUID(),
1809 'type' => 'dfrn:relocate',
1810 'actor' => $owner['url'],
1811 'object' => $owner['url'],
1812 'published' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
1813 'instrument' => self::getService(),
1814 'to' => [ActivityPub::PUBLIC_COLLECTION],
1817 $signed = LDSignature::sign($data, $owner);
1819 Logger::log('Deliver profile relocation for user ' . $uid . ' to ' . $inbox . ' via ActivityPub', Logger::DEBUG);
1820 return HTTPSignature::transmit($signed, $inbox, $uid);
1824 * Transmits a profile deletion to a given inbox
1826 * @param integer $uid User ID
1827 * @param string $inbox Target inbox
1829 * @return boolean was the transmission successful?
1830 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1832 public static function sendProfileDeletion($uid, $inbox)
1834 $owner = User::getOwnerDataById($uid);
1836 if (empty($owner)) {
1837 Logger::error('No owner data found, the deletion message cannot be processed.', ['user' => $uid]);
1841 if (empty($owner['uprvkey'])) {
1842 Logger::error('No private key for owner found, the deletion message cannot be processed.', ['user' => $uid]);
1846 $data = ['@context' => ActivityPub::CONTEXT,
1847 'id' => DI::baseUrl() . '/activity/' . System::createGUID(),
1849 'actor' => $owner['url'],
1850 'object' => $owner['url'],
1851 'published' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
1852 'instrument' => self::getService(),
1853 'to' => [ActivityPub::PUBLIC_COLLECTION],
1856 $signed = LDSignature::sign($data, $owner);
1858 Logger::log('Deliver profile deletion for user ' . $uid . ' to ' . $inbox . ' via ActivityPub', Logger::DEBUG);
1859 return HTTPSignature::transmit($signed, $inbox, $uid);
1863 * Transmits a profile change to a given inbox
1865 * @param integer $uid User ID
1866 * @param string $inbox Target inbox
1868 * @return boolean was the transmission successful?
1869 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1870 * @throws \ImagickException
1872 public static function sendProfileUpdate($uid, $inbox)
1874 $owner = User::getOwnerDataById($uid);
1875 $profile = APContact::getByURL($owner['url']);
1877 $data = ['@context' => ActivityPub::CONTEXT,
1878 'id' => DI::baseUrl() . '/activity/' . System::createGUID(),
1880 'actor' => $owner['url'],
1881 'object' => self::getProfile($uid),
1882 'published' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
1883 'instrument' => self::getService(),
1884 'to' => [$profile['followers']],
1887 $signed = LDSignature::sign($data, $owner);
1889 Logger::log('Deliver profile update for user ' . $uid . ' to ' . $inbox . ' via ActivityPub', Logger::DEBUG);
1890 return HTTPSignature::transmit($signed, $inbox, $uid);
1894 * Transmits a given activity to a target
1896 * @param string $activity Type name
1897 * @param string $target Target profile
1898 * @param integer $uid User ID
1900 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1901 * @throws \ImagickException
1902 * @throws \Exception
1904 public static function sendActivity($activity, $target, $uid, $id = '')
1906 $profile = APContact::getByURL($target);
1907 if (empty($profile['inbox'])) {
1908 Logger::warning('No inbox found for target', ['target' => $target, 'profile' => $profile]);
1912 $owner = User::getOwnerDataById($uid);
1915 $id = DI::baseUrl() . '/activity/' . System::createGUID();
1918 $data = ['@context' => ActivityPub::CONTEXT,
1920 'type' => $activity,
1921 'actor' => $owner['url'],
1922 'object' => $profile['url'],
1923 'instrument' => self::getService(),
1924 'to' => [$profile['url']]];
1926 Logger::log('Sending activity ' . $activity . ' to ' . $target . ' for user ' . $uid, Logger::DEBUG);
1928 $signed = LDSignature::sign($data, $owner);
1929 return HTTPSignature::transmit($signed, $profile['inbox'], $uid);
1933 * Transmits a "follow object" activity to a target
1934 * This is a preparation for sending automated "follow" requests when receiving "Announce" messages
1936 * @param string $object Object URL
1937 * @param string $target Target profile
1938 * @param integer $uid User ID
1940 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1941 * @throws \ImagickException
1942 * @throws \Exception
1944 public static function sendFollowObject($object, $target, $uid = 0)
1946 $profile = APContact::getByURL($target);
1947 if (empty($profile['inbox'])) {
1948 Logger::warning('No inbox found for target', ['target' => $target, 'profile' => $profile]);
1953 // Fetch the list of administrators
1954 $admin_mail = explode(',', str_replace(' ', '', DI::config()->get('config', 'admin_email')));
1956 // We need to use some user as a sender. It doesn't care who it will send. We will use an administrator account.
1957 $condition = ['verified' => true, 'blocked' => false, 'account_removed' => false, 'account_expired' => false, 'email' => $admin_mail];
1958 $first_user = DBA::selectFirst('user', ['uid'], $condition);
1959 $uid = $first_user['uid'];
1962 $condition = ['verb' => Activity::FOLLOW, 'uid' => 0, 'parent-uri' => $object,
1963 'author-id' => Contact::getPublicIdByUserId($uid)];
1964 if (Post::exists($condition)) {
1965 Logger::log('Follow for ' . $object . ' for user ' . $uid . ' does already exist.', Logger::DEBUG);
1969 $owner = User::getOwnerDataById($uid);
1971 $data = ['@context' => ActivityPub::CONTEXT,
1972 'id' => DI::baseUrl() . '/activity/' . System::createGUID(),
1974 'actor' => $owner['url'],
1975 'object' => $object,
1976 'instrument' => self::getService(),
1977 'to' => [$profile['url']]];
1979 Logger::log('Sending follow ' . $object . ' to ' . $target . ' for user ' . $uid, Logger::DEBUG);
1981 $signed = LDSignature::sign($data, $owner);
1982 return HTTPSignature::transmit($signed, $profile['inbox'], $uid);
1986 * Transmit a message that the contact request had been accepted
1988 * @param string $target Target profile
1990 * @param integer $uid User ID
1991 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1992 * @throws \ImagickException
1994 public static function sendContactAccept($target, $id, $uid)
1996 $profile = APContact::getByURL($target);
1997 if (empty($profile['inbox'])) {
1998 Logger::warning('No inbox found for target', ['target' => $target, 'profile' => $profile]);
2002 $owner = User::getOwnerDataById($uid);
2003 $data = ['@context' => ActivityPub::CONTEXT,
2004 'id' => DI::baseUrl() . '/activity/' . System::createGUID(),
2006 'actor' => $owner['url'],
2008 'id' => (string)$id,
2010 'actor' => $profile['url'],
2011 'object' => $owner['url']
2013 'instrument' => self::getService(),
2014 'to' => [$profile['url']]];
2016 Logger::debug('Sending accept to ' . $target . ' for user ' . $uid . ' with id ' . $id);
2018 $signed = LDSignature::sign($data, $owner);
2019 HTTPSignature::transmit($signed, $profile['inbox'], $uid);
2023 * Reject a contact request or terminates the contact relation
2025 * @param string $target Target profile
2027 * @param integer $uid User ID
2028 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2029 * @throws \ImagickException
2031 public static function sendContactReject($target, $id, $uid)
2033 $profile = APContact::getByURL($target);
2034 if (empty($profile['inbox'])) {
2035 Logger::warning('No inbox found for target', ['target' => $target, 'profile' => $profile]);
2039 $owner = User::getOwnerDataById($uid);
2040 $data = ['@context' => ActivityPub::CONTEXT,
2041 'id' => DI::baseUrl() . '/activity/' . System::createGUID(),
2043 'actor' => $owner['url'],
2045 'id' => (string)$id,
2047 'actor' => $profile['url'],
2048 'object' => $owner['url']
2050 'instrument' => self::getService(),
2051 'to' => [$profile['url']]];
2053 Logger::debug('Sending reject to ' . $target . ' for user ' . $uid . ' with id ' . $id);
2055 $signed = LDSignature::sign($data, $owner);
2056 HTTPSignature::transmit($signed, $profile['inbox'], $uid);
2060 * Transmits a message that we don't want to follow this contact anymore
2062 * @param string $target Target profile
2063 * @param integer $uid User ID
2064 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2065 * @throws \ImagickException
2066 * @throws \Exception
2067 * @return bool success
2069 public static function sendContactUndo($target, $cid, $uid)
2071 $profile = APContact::getByURL($target);
2072 if (empty($profile['inbox'])) {
2073 Logger::warning('No inbox found for target', ['target' => $target, 'profile' => $profile]);
2077 $object_id = self::activityIDFromContact($cid);
2078 if (empty($object_id)) {
2082 $id = DI::baseUrl() . '/activity/' . System::createGUID();
2084 $owner = User::getOwnerDataById($uid);
2085 $data = ['@context' => ActivityPub::CONTEXT,
2088 'actor' => $owner['url'],
2089 'object' => ['id' => $object_id, 'type' => 'Follow',
2090 'actor' => $owner['url'],
2091 'object' => $profile['url']],
2092 'instrument' => self::getService(),
2093 'to' => [$profile['url']]];
2095 Logger::log('Sending undo to ' . $target . ' for user ' . $uid . ' with id ' . $id, Logger::DEBUG);
2097 $signed = LDSignature::sign($data, $owner);
2098 return HTTPSignature::transmit($signed, $profile['inbox'], $uid);
2101 private static function prependMentions($body, int $uriid, string $authorLink)
2105 foreach (Tag::getByURIId($uriid, [Tag::IMPLICIT_MENTION]) as $tag) {
2106 $profile = Contact::getByURL($tag['url'], false, ['addr', 'contact-type', 'nick']);
2107 if (!empty($profile['addr'])
2108 && $profile['contact-type'] != Contact::TYPE_COMMUNITY
2109 && !strstr($body, $profile['addr'])
2110 && !strstr($body, $tag['url'])
2111 && $tag['url'] !== $authorLink
2113 $mentions[] = '@[url=' . $tag['url'] . ']' . $profile['nick'] . '[/url]';
2117 $mentions[] = $body;
2119 return implode(' ', $mentions);