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 $condition = ['private' => [Item::PUBLIC, Item::UNLISTED]];
240 if (!empty($requester)) {
241 $requester_id = Contact::getIdForURL($requester, $owner['uid']);
242 if (!empty($requester_id)) {
243 $permissionSets = DI::permissionSet()->selectByContactId($requester_id, $owner['uid']);
244 if (!empty($permissionSets)) {
245 $condition = ['psid' => array_merge($permissionSets->column('id'),
246 [DI::permissionSet()->getIdFromACL($owner['uid'], '', '', '', '')])];
251 $condition = array_merge($condition,
252 ['uid' => $owner['uid'],
253 'author-id' => Contact::getIdForURL($owner['url'], 0, false),
254 'gravity' => [GRAVITY_PARENT, GRAVITY_COMMENT],
255 'network' => Protocol::FEDERATED,
256 'parent-network' => Protocol::FEDERATED,
261 $count = Post::count($condition);
263 $data = ['@context' => ActivityPub::CONTEXT];
264 $data['id'] = DI::baseUrl() . '/outbox/' . $owner['nickname'];
265 $data['type'] = 'OrderedCollection';
266 $data['totalItems'] = $count;
269 $data['first'] = DI::baseUrl() . '/outbox/' . $owner['nickname'] . '?page=1';
271 $data['type'] = 'OrderedCollectionPage';
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)
319 $owner = User::getOwnerDataById($uid);
321 $data = ['@context' => ActivityPub::CONTEXT];
322 $data['id'] = $owner['url'];
324 if (!empty($owner['guid'])) {
325 $data['diaspora:guid'] = $owner['guid'];
328 $data['type'] = ActivityPub::ACCOUNT_TYPES[$owner['account-type']];
331 $data['following'] = DI::baseUrl() . '/following/' . $owner['nick'];
332 $data['followers'] = DI::baseUrl() . '/followers/' . $owner['nick'];
333 $data['inbox'] = DI::baseUrl() . '/inbox/' . $owner['nick'];
334 $data['outbox'] = DI::baseUrl() . '/outbox/' . $owner['nick'];
336 $data['inbox'] = DI::baseUrl() . '/friendica/inbox';
339 $data['preferredUsername'] = $owner['nick'];
340 $data['name'] = $owner['name'];
342 if (!empty($owner['country-name'] . $owner['region'] . $owner['locality'])) {
343 $data['vcard:hasAddress'] = ['@type' => 'vcard:Home', 'vcard:country-name' => $owner['country-name'],
344 'vcard:region' => $owner['region'], 'vcard:locality' => $owner['locality']];
347 if (!empty($owner['about'])) {
348 $data['summary'] = BBCode::convertForUriId($owner['uri-id'] ?? 0, $owner['about'], BBCode::EXTERNAL);
351 $data['url'] = $owner['url'];
352 $data['manuallyApprovesFollowers'] = in_array($owner['page-flags'], [User::PAGE_FLAGS_NORMAL, User::PAGE_FLAGS_PRVGROUP]);
353 $data['discoverable'] = $owner['net-publish'];
354 $data['publicKey'] = ['id' => $owner['url'] . '#main-key',
355 'owner' => $owner['url'],
356 'publicKeyPem' => $owner['pubkey']];
357 $data['endpoints'] = ['sharedInbox' => DI::baseUrl() . '/inbox'];
358 $data['icon'] = ['type' => 'Image', 'url' => Contact::getAvatarUrlForId($owner['id'], '', $owner['updated'])];
360 $resourceid = Photo::ridFromURI($owner['photo']);
361 if (!empty($resourceid)) {
362 $photo = Photo::selectFirst(['type'], ["resource-id" => $resourceid]);
363 if (!empty($photo['type'])) {
364 $data['icon']['mediaType'] = $photo['type'];
368 if (!empty($owner['header'])) {
369 $data['image'] = ['type' => 'Image', 'url' => Contact::getHeaderUrlForId($owner['id'], '', $owner['updated'])];
371 $resourceid = Photo::ridFromURI($owner['header']);
372 if (!empty($resourceid)) {
373 $photo = Photo::selectFirst(['type'], ["resource-id" => $resourceid]);
374 if (!empty($photo['type'])) {
375 $data['image']['mediaType'] = $photo['type'];
380 $data['generator'] = self::getService();
382 // tags: https://kitty.town/@inmysocks/100656097926961126.json
387 * @param string $username
389 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
391 public static function getDeletedUser($username)
394 '@context' => ActivityPub::CONTEXT,
395 'id' => DI::baseUrl() . '/profile/' . $username,
396 'type' => 'Tombstone',
397 'published' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
398 'updated' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
399 'deleted' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
404 * Returns an array with permissions of a given item array
408 * @return array with permissions
409 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
410 * @throws \ImagickException
412 private static function fetchPermissionBlockFromConversation($item)
414 if (empty($item['thr-parent'])) {
418 $condition = ['item-uri' => $item['thr-parent'], 'protocol' => Conversation::PARCEL_ACTIVITYPUB];
419 $conversation = DBA::selectFirst('conversation', ['source'], $condition);
420 if (!DBA::isResult($conversation)) {
424 $activity = json_decode($conversation['source'], true);
426 $actor = JsonLD::fetchElement($activity, 'actor', 'id');
427 if (!empty($actor)) {
428 $permissions['to'][] = $actor;
429 $profile = APContact::getByURL($actor);
434 $item_profile = APContact::getByURL($item['author-link']);
435 $exclude[] = $item['author-link'];
437 if ($item['gravity'] == GRAVITY_PARENT) {
438 $exclude[] = $item['owner-link'];
441 foreach (['to', 'cc', 'bto', 'bcc'] as $element) {
442 if (empty($activity[$element])) {
445 if (is_string($activity[$element])) {
446 $activity[$element] = [$activity[$element]];
449 foreach ($activity[$element] as $receiver) {
450 if (empty($receiver)) {
454 if (!empty($profile['followers']) && $receiver == $profile['followers'] && !empty($item_profile['followers'])) {
455 $permissions[$element][] = $item_profile['followers'];
456 } elseif (!in_array($receiver, $exclude)) {
457 $permissions[$element][] = $receiver;
465 * Check if the given item id is from ActivityPub
467 * @param integer $item_id
468 * @return boolean "true" if the post is from ActivityPub
470 private static function isAPPost(int $item_id)
472 if (empty($item_id)) {
476 return Post::exists(['id' => $item_id, 'network' => Protocol::ACTIVITYPUB]);
480 * Creates an array of permissions from an item thread
482 * @param array $item Item array
483 * @param boolean $blindcopy addressing via "bcc" or "cc"?
484 * @param integer $last_id Last item id for adding receivers
485 * @param boolean $forum_mode "true" means that we are sending content to a forum
487 * @return array with permission data
488 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
489 * @throws \ImagickException
491 private static function createPermissionBlockForItem($item, $blindcopy, $last_id = 0, $forum_mode = false)
494 $last_id = $item['id'];
499 // Check if we should always deliver our stuff via BCC
500 if (!empty($item['uid'])) {
501 $profile = User::getOwnerDataById($item['uid']);
502 if (!empty($profile)) {
503 $always_bcc = $profile['hide-friends'];
507 if (DI::config()->get('system', 'ap_always_bcc')) {
511 if (self::isAnnounce($item) || DI::config()->get('debug', 'total_ap_delivery') || self::isAPPost($last_id)) {
512 // Will be activated in a later step
513 $networks = Protocol::FEDERATED;
515 // For now only send to these contacts:
516 $networks = [Protocol::ACTIVITYPUB, Protocol::OSTATUS];
519 $data = ['to' => [], 'cc' => [], 'bcc' => []];
521 if ($item['gravity'] == GRAVITY_PARENT) {
522 $actor_profile = APContact::getByURL($item['owner-link']);
524 $actor_profile = APContact::getByURL($item['author-link']);
529 $terms = Tag::getByURIId($item['uri-id'], [Tag::MENTION, Tag::IMPLICIT_MENTION, Tag::EXCLUSIVE_MENTION]);
531 if ($item['private'] != Item::PRIVATE) {
532 // Directly mention the original author upon a quoted reshare.
533 // Else just ensure that the original author receives the reshare.
534 $announce = self::getAnnounceArray($item);
535 if (!empty($announce['comment'])) {
536 $data['to'][] = $announce['actor']['url'];
537 } elseif (!empty($announce)) {
538 $data['cc'][] = $announce['actor']['url'];
541 $data = array_merge($data, self::fetchPermissionBlockFromConversation($item));
543 // Check if the item is completely public or unlisted
544 if ($item['private'] == Item::PUBLIC) {
545 $data['to'][] = ActivityPub::PUBLIC_COLLECTION;
547 $data['cc'][] = ActivityPub::PUBLIC_COLLECTION;
550 foreach ($terms as $term) {
551 $profile = APContact::getByURL($term['url'], false);
552 if (!empty($profile)) {
553 if ($term['type'] == Tag::EXCLUSIVE_MENTION) {
555 if (!empty($profile['followers']) && ($profile['type'] == 'Group')) {
556 $data['cc'][] = $profile['followers'];
559 $data['to'][] = $profile['url'];
563 $receiver_list = Item::enumeratePermissions($item, true);
565 foreach ($terms as $term) {
566 $cid = Contact::getIdForURL($term['url'], $item['uid']);
567 if (!empty($cid) && in_array($cid, $receiver_list)) {
568 $contact = DBA::selectFirst('contact', ['url', 'network', 'protocol', 'gsid'], ['id' => $cid, 'network' => Protocol::FEDERATED]);
569 if (!DBA::isResult($contact) || !self::isAPContact($contact, $networks)) {
573 if (!empty($profile = APContact::getByURL($contact['url'], false))) {
574 $data['to'][] = $profile['url'];
579 foreach ($receiver_list as $receiver) {
580 $contact = DBA::selectFirst('contact', ['url', 'hidden', 'network', 'protocol', 'gsid'], ['id' => $receiver, 'network' => Protocol::FEDERATED]);
581 if (!DBA::isResult($contact) || !self::isAPContact($contact, $networks)) {
585 if (!empty($profile = APContact::getByURL($contact['url'], false))) {
586 if ($contact['hidden'] || $always_bcc) {
587 $data['bcc'][] = $profile['url'];
589 $data['cc'][] = $profile['url'];
595 if (!empty($item['parent'])) {
596 $parents = Post::select(['id', 'author-link', 'owner-link', 'gravity', 'uri'], ['parent' => $item['parent']]);
597 while ($parent = Post::fetch($parents)) {
598 if ($parent['gravity'] == GRAVITY_PARENT) {
599 $profile = APContact::getByURL($parent['owner-link'], false);
600 if (!empty($profile)) {
601 if ($item['gravity'] != GRAVITY_PARENT) {
602 // Comments to forums are directed to the forum
603 // But comments to forums aren't directed to the followers collection
604 // This rule is only valid when the actor isn't the forum.
605 // The forum needs to transmit their content to their followers.
606 if (($profile['type'] == 'Group') && ($profile['url'] != ($actor_profile['url'] ?? ''))) {
607 $data['to'][] = $profile['url'];
609 $data['cc'][] = $profile['url'];
610 if (($item['private'] != Item::PRIVATE) && !empty($actor_profile['followers'])) {
611 $data['cc'][] = $actor_profile['followers'];
614 } elseif (!$exclusive) {
615 // Public thread parent post always are directed to the followers.
616 // This mustn't be done by posts that are directed to forum servers via the exclusive mention.
617 // But possibly in that case we could add the "followers" collection of the forum to the message.
618 if (($item['private'] != Item::PRIVATE) && !$forum_mode) {
619 $data['cc'][] = $actor_profile['followers'];
625 // Don't include data from future posts
626 if ($parent['id'] >= $last_id) {
630 $profile = APContact::getByURL($parent['author-link'], false);
631 if (!empty($profile)) {
632 if (($profile['type'] == 'Group') || ($parent['uri'] == $item['thr-parent'])) {
633 $data['to'][] = $profile['url'];
635 $data['cc'][] = $profile['url'];
639 DBA::close($parents);
642 $data['to'] = array_unique($data['to']);
643 $data['cc'] = array_unique($data['cc']);
644 $data['bcc'] = array_unique($data['bcc']);
646 if (($key = array_search($item['author-link'], $data['to'])) !== false) {
647 unset($data['to'][$key]);
650 if (($key = array_search($item['author-link'], $data['cc'])) !== false) {
651 unset($data['cc'][$key]);
654 if (($key = array_search($item['author-link'], $data['bcc'])) !== false) {
655 unset($data['bcc'][$key]);
658 foreach ($data['to'] as $to) {
659 if (($key = array_search($to, $data['cc'])) !== false) {
660 unset($data['cc'][$key]);
663 if (($key = array_search($to, $data['bcc'])) !== false) {
664 unset($data['bcc'][$key]);
668 foreach ($data['cc'] as $cc) {
669 if (($key = array_search($cc, $data['bcc'])) !== false) {
670 unset($data['bcc'][$key]);
674 $receivers = ['to' => array_values($data['to']), 'cc' => array_values($data['cc']), 'bcc' => array_values($data['bcc'])];
677 unset($receivers['bcc']);
684 * Check if an inbox is archived
686 * @param string $url Inbox url
688 * @return boolean "true" if inbox is archived
690 public static function archivedInbox($url)
692 return DBA::exists('inbox-status', ['url' => $url, 'archive' => true]);
696 * Check if a given contact should be delivered via AP
698 * @param array $contact
699 * @param array $networks
703 private static function isAPContact(array $contact, array $networks)
705 if (in_array($contact['network'], $networks) || ($contact['protocol'] == Protocol::ACTIVITYPUB)) {
709 return GServer::getProtocol($contact['gsid'] ?? 0) == Post\DeliveryData::ACTIVITYPUB;
713 * Fetches a list of inboxes of followers of a given user
715 * @param integer $uid User ID
716 * @param boolean $personal fetch personal inboxes
717 * @param boolean $all_ap Retrieve all AP enabled inboxes
719 * @return array of follower inboxes
720 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
721 * @throws \ImagickException
723 public static function fetchTargetInboxesforUser($uid, $personal = false, bool $all_ap = false)
729 if (!empty($item['uid'])) {
730 $profile = User::getOwnerDataById($item['uid']);
731 if (!empty($profile)) {
732 $isforum = $profile['account-type'] == User::ACCOUNT_TYPE_COMMUNITY;
736 if (DI::config()->get('debug', 'total_ap_delivery') || $all_ap) {
737 // Will be activated in a later step
738 $networks = Protocol::FEDERATED;
740 // For now only send to these contacts:
741 $networks = [Protocol::ACTIVITYPUB, Protocol::OSTATUS];
744 $condition = ['uid' => $uid, 'archive' => false, 'pending' => false, 'blocked' => false, 'network' => Protocol::FEDERATED];
747 $condition['rel'] = [Contact::FOLLOWER, Contact::FRIEND];
750 $contacts = DBA::select('contact', ['id', 'url', 'network', 'protocol', 'gsid'], $condition);
751 while ($contact = DBA::fetch($contacts)) {
752 if (!self::isAPContact($contact, $networks)) {
756 if ($isforum && ($contact['network'] == Protocol::DFRN)) {
760 if (Network::isUrlBlocked($contact['url'])) {
764 $profile = APContact::getByURL($contact['url'], false);
765 if (!empty($profile)) {
766 if (empty($profile['sharedinbox']) || $personal || Contact::isLocal($contact['url'])) {
767 $target = $profile['inbox'];
769 $target = $profile['sharedinbox'];
771 if (!self::archivedInbox($target)) {
772 $inboxes[$target][] = $contact['id'];
776 DBA::close($contacts);
782 * Fetches an array of inboxes for the given item and user
784 * @param array $item Item array
785 * @param integer $uid User ID
786 * @param boolean $personal fetch personal inboxes
787 * @param integer $last_id Last item id for adding receivers
788 * @param boolean $forum_mode "true" means that we are sending content to a forum
789 * @return array with inboxes
790 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
791 * @throws \ImagickException
793 public static function fetchTargetInboxes($item, $uid, $personal = false, $last_id = 0, $forum_mode = false)
795 $permissions = self::createPermissionBlockForItem($item, true, $last_id, $forum_mode);
796 if (empty($permissions)) {
802 if ($item['gravity'] == GRAVITY_ACTIVITY) {
803 $item_profile = APContact::getByURL($item['author-link'], false);
805 $item_profile = APContact::getByURL($item['owner-link'], false);
808 if (empty($item_profile)) {
812 $profile_uid = User::getIdForURL($item_profile['url']);
814 foreach (['to', 'cc', 'bto', 'bcc'] as $element) {
815 if (empty($permissions[$element])) {
819 $blindcopy = in_array($element, ['bto', 'bcc']);
821 foreach ($permissions[$element] as $receiver) {
822 if (empty($receiver) || Network::isUrlBlocked($receiver)) {
826 if ($item_profile && ($receiver == $item_profile['followers']) && ($uid == $profile_uid)) {
827 $inboxes = array_merge($inboxes, self::fetchTargetInboxesforUser($uid, $personal, self::isAPPost($last_id)));
829 $profile = APContact::getByURL($receiver, false);
830 if (!empty($profile)) {
831 $contact = Contact::getByURLForUser($receiver, $uid, false, ['id']);
833 if (empty($profile['sharedinbox']) || $personal || $blindcopy || Contact::isLocal($receiver)) {
834 $target = $profile['inbox'];
836 $target = $profile['sharedinbox'];
838 if (!self::archivedInbox($target)) {
839 $inboxes[$target][] = $contact['id'] ?? 0;
850 * Creates an array in the structure of the item table for a given mail id
852 * @param integer $mail_id
857 public static function ItemArrayFromMail($mail_id, $use_title = false)
859 $mail = DBA::selectFirst('mail', [], ['id' => $mail_id]);
860 if (!DBA::isResult($mail)) {
864 $reply = DBA::selectFirst('mail', ['uri', 'uri-id', 'from-url'], ['parent-uri' => $mail['parent-uri'], 'reply' => false]);
866 // Making the post more compatible for Mastodon by:
867 // - Making it a note and not an article (no title)
868 // - Moving the title into the "summary" field that is used as a "content warning"
871 $mail['body'] = '[abstract]' . $mail['title'] . "[/abstract]\n" . $mail['body'];
875 $mail['author-link'] = $mail['owner-link'] = $mail['from-url'];
876 $mail['owner-id'] = $mail['author-id'];
877 $mail['allow_cid'] = '<'.$mail['contact-id'].'>';
878 $mail['allow_gid'] = '';
879 $mail['deny_cid'] = '';
880 $mail['deny_gid'] = '';
881 $mail['private'] = Item::PRIVATE;
882 $mail['deleted'] = false;
883 $mail['edited'] = $mail['created'];
884 $mail['plink'] = DI::baseUrl() . '/message/' . $mail['id'];
885 $mail['parent-uri'] = $reply['uri'];
886 $mail['parent-uri-id'] = $reply['uri-id'];
887 $mail['parent-author-id'] = Contact::getIdForURL($reply['from-url'], 0, false);
888 $mail['gravity'] = ($mail['reply'] ? GRAVITY_COMMENT: GRAVITY_PARENT);
889 $mail['event-type'] = '';
890 $mail['language'] = '';
897 * Creates an activity array for a given mail id
899 * @param integer $mail_id
900 * @param boolean $object_mode Is the activity item is used inside another object?
902 * @return array of activity
905 public static function createActivityFromMail($mail_id, $object_mode = false)
907 $mail = self::ItemArrayFromMail($mail_id);
911 $object = self::createNote($mail);
914 $data = ['@context' => ActivityPub::CONTEXT];
919 $data['id'] = $mail['uri'] . '/Create';
920 $data['type'] = 'Create';
921 $data['actor'] = $mail['author-link'];
922 $data['published'] = DateTimeFormat::utc($mail['created'] . '+00:00', DateTimeFormat::ATOM);
923 $data['instrument'] = self::getService();
924 $data = array_merge($data, self::createPermissionBlockForItem($mail, true));
926 if (empty($data['to']) && !empty($data['cc'])) {
927 $data['to'] = $data['cc'];
930 if (empty($data['to']) && !empty($data['bcc'])) {
931 $data['to'] = $data['bcc'];
937 $object['to'] = $data['to'];
938 $object['tag'] = [['type' => 'Mention', 'href' => $object['to'][0], 'name' => '']];
940 unset($object['cc']);
941 unset($object['bcc']);
943 $data['directMessage'] = true;
945 $data['object'] = $object;
947 $owner = User::getOwnerDataById($mail['uid']);
949 if (!$object_mode && !empty($owner)) {
950 return LDSignature::sign($data, $owner);
957 * Returns the activity type of a given item
961 * @return string with activity type
962 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
963 * @throws \ImagickException
965 private static function getTypeOfItem($item)
969 // Only check for a reshare, if it is a real reshare and no quoted reshare
970 if (strpos($item['body'], "[share") === 0) {
971 $announce = self::getAnnounceArray($item);
972 $reshared = !empty($announce);
977 } elseif ($item['verb'] == Activity::POST) {
978 if ($item['created'] == $item['edited']) {
983 } elseif ($item['verb'] == Activity::LIKE) {
985 } elseif ($item['verb'] == Activity::DISLIKE) {
987 } elseif ($item['verb'] == Activity::ATTEND) {
989 } elseif ($item['verb'] == Activity::ATTENDNO) {
991 } elseif ($item['verb'] == Activity::ATTENDMAYBE) {
992 $type = 'TentativeAccept';
993 } elseif ($item['verb'] == Activity::FOLLOW) {
995 } elseif ($item['verb'] == Activity::TAG) {
997 } elseif ($item['verb'] == Activity::ANNOUNCE) {
1007 * Creates the activity or fetches it from the cache
1009 * @param integer $item_id
1010 * @param boolean $force Force new cache entry
1012 * @return array with the activity
1013 * @throws \Exception
1015 public static function createCachedActivityFromItem($item_id, $force = false)
1017 $cachekey = 'APDelivery:createActivity:' . $item_id;
1020 $data = DI::cache()->get($cachekey);
1021 if (!is_null($data)) {
1026 $data = self::createActivityFromItem($item_id);
1028 DI::cache()->set($cachekey, $data, Duration::QUARTER_HOUR);
1033 * Creates an activity array for a given item id
1035 * @param integer $item_id
1036 * @param boolean $object_mode Is the activity item is used inside another object?
1038 * @return false|array
1039 * @throws \Exception
1041 public static function createActivityFromItem(int $item_id, bool $object_mode = false)
1043 Logger::info('Fetching activity', ['item' => $item_id]);
1044 $item = Post::selectFirst(Item::DELIVER_FIELDLIST, ['id' => $item_id, 'parent-network' => Protocol::NATIVE_SUPPORT]);
1045 if (!DBA::isResult($item)) {
1049 // In case of a forum post ensure to return the original post if author and forum are on the same machine
1050 if (($item['gravity'] == GRAVITY_PARENT) && !empty($item['forum_mode'])) {
1051 $author = Contact::getById($item['author-id'], ['nurl']);
1052 if (!empty($author['nurl'])) {
1053 $self = Contact::selectFirst(['uid'], ['nurl' => $author['nurl'], 'self' => true]);
1054 if (!empty($self['uid'])) {
1055 $forum_item = Post::selectFirst(Item::DELIVER_FIELDLIST, ['uri-id' => $item['uri-id'], 'uid' => $self['uid']]);
1056 if (DBA::isResult($forum_item)) {
1057 $item = $forum_item;
1063 if (empty($item['uri-id'])) {
1064 Logger::warning('Item without uri-id', ['item' => $item]);
1068 if (!$item['deleted']) {
1069 $condition = ['item-uri' => $item['uri'], 'protocol' => Conversation::PARCEL_ACTIVITYPUB];
1070 $conversation = DBA::selectFirst('conversation', ['source'], $condition);
1071 if (!$item['origin'] && DBA::isResult($conversation)) {
1072 $data = json_decode($conversation['source'], true);
1073 if (!empty($data['type'])) {
1074 if (in_array($data['type'], ['Create', 'Update'])) {
1076 unset($data['@context']);
1077 unset($data['signature']);
1079 Logger::info('Return stored conversation', ['item' => $item_id]);
1081 } elseif (in_array('as:' . $data['type'], Receiver::CONTENT_TYPES)) {
1082 if (!empty($data['@context'])) {
1083 $context = $data['@context'];
1084 unset($data['@context']);
1086 unset($data['actor']);
1093 $type = self::getTypeOfItem($item);
1095 if (!$object_mode) {
1096 $data = ['@context' => $context ?? ActivityPub::CONTEXT];
1098 if ($item['deleted'] && ($item['gravity'] == GRAVITY_ACTIVITY)) {
1100 } elseif ($item['deleted']) {
1107 if ($type == 'Delete') {
1108 $data['id'] = Item::newURI($item['uid'], $item['guid']) . '/' . $type;;
1109 } elseif (($item['gravity'] == GRAVITY_ACTIVITY) && ($type != 'Undo')) {
1110 $data['id'] = $item['uri'];
1112 $data['id'] = $item['uri'] . '/' . $type;
1115 $data['type'] = $type;
1117 if (($type != 'Announce') || ($item['gravity'] != GRAVITY_PARENT)) {
1118 $data['actor'] = $item['author-link'];
1120 $data['actor'] = $item['owner-link'];
1123 $data['published'] = DateTimeFormat::utc($item['created'] . '+00:00', DateTimeFormat::ATOM);
1125 $data['instrument'] = self::getService();
1127 $data = array_merge($data, self::createPermissionBlockForItem($item, false));
1129 if (in_array($data['type'], ['Create', 'Update', 'Delete'])) {
1130 $data['object'] = $object ?? self::createNote($item);
1131 } elseif ($data['type'] == 'Add') {
1132 $data = self::createAddTag($item, $data);
1133 } elseif ($data['type'] == 'Announce') {
1134 if ($item['verb'] == ACTIVITY::ANNOUNCE) {
1135 $data['object'] = $item['thr-parent'];
1137 $data = self::createAnnounce($item, $data);
1139 } elseif ($data['type'] == 'Follow') {
1140 $data['object'] = $item['parent-uri'];
1141 } elseif ($data['type'] == 'Undo') {
1142 $data['object'] = self::createActivityFromItem($item_id, true);
1144 $data['diaspora:guid'] = $item['guid'];
1145 if (!empty($item['signed_text'])) {
1146 $data['diaspora:like'] = $item['signed_text'];
1148 $data['object'] = $item['thr-parent'];
1151 if (!empty($item['contact-uid'])) {
1152 $uid = $item['contact-uid'];
1154 $uid = $item['uid'];
1157 $owner = User::getOwnerDataById($uid);
1159 Logger::info('Fetched activity', ['item' => $item_id, 'uid' => $uid]);
1161 // We don't sign if we aren't the actor. This is important for relaying content especially for forums
1162 if (!$object_mode && !empty($owner) && ($data['actor'] == $owner['url'])) {
1163 return LDSignature::sign($data, $owner);
1168 /// @todo Create "conversation" entry
1172 * Creates a location entry for a given item array
1174 * @param array $item
1176 * @return array with location array
1178 private static function createLocation($item)
1180 $location = ['type' => 'Place'];
1182 if (!empty($item['location'])) {
1183 $location['name'] = $item['location'];
1188 if (empty($item['coord'])) {
1189 $coord = Map::getCoordinates($item['location']);
1191 $coords = explode(' ', $item['coord']);
1192 if (count($coords) == 2) {
1193 $coord = ['lat' => $coords[0], 'lon' => $coords[1]];
1197 if (!empty($coord['lat']) && !empty($coord['lon'])) {
1198 $location['latitude'] = $coord['lat'];
1199 $location['longitude'] = $coord['lon'];
1206 * Returns a tag array for a given item array
1208 * @param array $item
1210 * @return array of tags
1211 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1213 private static function createTagList($item)
1217 $terms = Tag::getByURIId($item['uri-id'], [Tag::HASHTAG, Tag::MENTION, Tag::IMPLICIT_MENTION, Tag::EXCLUSIVE_MENTION]);
1218 foreach ($terms as $term) {
1219 if ($term['type'] == Tag::HASHTAG) {
1220 $url = DI::baseUrl() . '/search?tag=' . urlencode($term['name']);
1221 $tags[] = ['type' => 'Hashtag', 'href' => $url, 'name' => '#' . $term['name']];
1223 $contact = Contact::getByURL($term['url'], false, ['addr']);
1224 if (empty($contact)) {
1227 if (!empty($contact['addr'])) {
1228 $mention = '@' . $contact['addr'];
1230 $mention = '@' . $term['url'];
1233 $tags[] = ['type' => 'Mention', 'href' => $term['url'], 'name' => $mention];
1237 $announce = self::getAnnounceArray($item);
1238 // Mention the original author upon commented reshares
1239 if (!empty($announce['comment'])) {
1240 $tags[] = ['type' => 'Mention', 'href' => $announce['actor']['url'], 'name' => '@' . $announce['actor']['addr']];
1247 * Adds attachment data to the JSON document
1249 * @param array $item Data of the item that is to be posted
1250 * @param string $type Object type
1252 * @return array with attachment data
1253 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1255 private static function createAttachmentList($item, $type)
1259 $uriids = [$item['uri-id']];
1260 $shared = BBCode::fetchShareAttributes($item['body']);
1261 if (!empty($shared['guid'])) {
1262 $shared_item = Post::selectFirst(['uri-id'], ['guid' => $shared['guid']]);
1263 if (!empty($shared_item['uri-id'])) {
1264 $uriids[] = $shared_item['uri-id'];
1269 foreach ($uriids as $uriid) {
1270 foreach (Post\Media::getByURIId($uriid, [Post\Media::DOCUMENT, Post\Media::TORRENT]) as $attachment) {
1271 if (in_array($attachment['url'], $urls)) {
1274 $urls[] = $attachment['url'];
1276 $attach = ['type' => 'Document',
1277 'mediaType' => $attachment['mimetype'],
1278 'url' => $attachment['url'],
1279 'name' => $attachment['description']];
1281 if (!empty($attachment['height'])) {
1282 $attach['height'] = $attachment['height'];
1285 if (!empty($attachment['width'])) {
1286 $attach['width'] = $attachment['width'];
1289 if (!empty($attachment['preview'])) {
1290 $attach['image'] = $attachment['preview'];
1293 $attachments[] = $attach;
1297 if ($type != 'Note') {
1298 return $attachments;
1301 foreach ($uriids as $uriid) {
1302 foreach (Post\Media::getByURIId($uriid, [Post\Media::AUDIO, Post\Media::IMAGE, Post\Media::VIDEO]) as $attachment) {
1303 if (in_array($attachment['url'], $urls)) {
1306 $urls[] = $attachment['url'];
1308 $attach = ['type' => 'Document',
1309 'mediaType' => $attachment['mimetype'],
1310 'url' => $attachment['url'],
1311 'name' => $attachment['description']];
1313 if (!empty($attachment['height'])) {
1314 $attach['height'] = $attachment['height'];
1317 if (!empty($attachment['width'])) {
1318 $attach['width'] = $attachment['width'];
1321 if (!empty($attachment['preview'])) {
1322 $attach['image'] = $attachment['preview'];
1325 $attachments[] = $attach;
1327 // Currently deactivated, since it creates side effects on Mastodon and Pleroma.
1328 // It will be activated, once this cleared.
1330 foreach (Post\Media::getByURIId($uriid, [Post\Media::HTML]) as $attachment) {
1331 if (in_array($attachment['url'], $urls)) {
1334 $urls[] = $attachment['url'];
1336 $attachments[] = ['type' => 'Page',
1337 'mediaType' => $attachment['mimetype'],
1338 'url' => $attachment['url'],
1339 'name' => $attachment['description']];
1343 return $attachments;
1347 * Callback function to replace a Friendica style mention in a mention for a summary
1349 * @param array $match Matching values for the callback
1350 * @return string Replaced mention
1351 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1353 private static function mentionAddrCallback($match)
1355 if (empty($match[1])) {
1359 $data = Contact::getByURL($match[1], false, ['addr']);
1360 if (empty($data['addr'])) {
1364 return '@' . $data['addr'];
1368 * Remove image elements since they are added as attachment
1370 * @param string $body
1372 * @return string with removed images
1374 private static function removePictures($body)
1376 // Simplify image codes
1377 $body = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '[img]$3[/img]', $body);
1378 $body = preg_replace("/\[img\=(.*?)\](.*?)\[\/img\]/ism", '[img]$1[/img]', $body);
1380 // Now remove local links
1381 $body = preg_replace_callback(
1382 '/\[url=([^\[\]]*)\]\[img\](.*)\[\/img\]\[\/url\]/Usi',
1384 // We remove the link when it is a link to a local photo page
1385 if (Photo::isLocalPage($match[1])) {
1388 // otherwise we just return the link
1389 return '[url]' . $match[1] . '[/url]';
1394 // Remove all pictures
1395 $body = preg_replace("/\[img\]([^\[\]]*)\[\/img\]/Usi", '', $body);
1401 * Fetches the "context" value for a givem item array from the "conversation" table
1403 * @param array $item
1405 * @return string with context url
1406 * @throws \Exception
1408 private static function fetchContextURLForItem($item)
1410 $conversation = DBA::selectFirst('conversation', ['conversation-href', 'conversation-uri'], ['item-uri' => $item['parent-uri']]);
1411 if (DBA::isResult($conversation) && !empty($conversation['conversation-href'])) {
1412 $context_uri = $conversation['conversation-href'];
1413 } elseif (DBA::isResult($conversation) && !empty($conversation['conversation-uri'])) {
1414 $context_uri = $conversation['conversation-uri'];
1416 $context_uri = $item['parent-uri'] . '#context';
1418 return $context_uri;
1422 * Returns if the post contains sensitive content ("nsfw")
1424 * @param integer $uri_id
1427 * @throws \Exception
1429 private static function isSensitive($uri_id)
1431 return DBA::exists('tag-view', ['uri-id' => $uri_id, 'name' => 'nsfw']);
1435 * Creates event data
1437 * @param array $item
1439 * @return array with the event data
1440 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1442 private static function createEvent($item)
1445 $event['name'] = $item['event-summary'];
1446 $event['content'] = BBCode::convertForUriId($item['uri-id'], $item['event-desc'], BBCode::ACTIVITYPUB);
1447 $event['startTime'] = DateTimeFormat::utc($item['event-start'] . '+00:00', DateTimeFormat::ATOM);
1449 if (!$item['event-nofinish']) {
1450 $event['endTime'] = DateTimeFormat::utc($item['event-finish'] . '+00:00', DateTimeFormat::ATOM);
1453 if (!empty($item['event-location'])) {
1454 $item['location'] = $item['event-location'];
1455 $event['location'] = self::createLocation($item);
1458 $event['dfrn:adjust'] = (bool)$item['event-adjust'];
1464 * Creates a note/article object array
1466 * @param array $item
1468 * @return array with the object data
1469 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1470 * @throws \ImagickException
1472 public static function createNote($item)
1478 if ($item['event-type'] == 'event') {
1480 } elseif (!empty($item['title'])) {
1486 if ($item['deleted']) {
1487 $type = 'Tombstone';
1491 $data['id'] = $item['uri'];
1492 $data['type'] = $type;
1494 if ($item['deleted']) {
1498 $data['summary'] = BBCode::toPlaintext(BBCode::getAbstract($item['body'], Protocol::ACTIVITYPUB));
1500 if ($item['uri'] != $item['thr-parent']) {
1501 $data['inReplyTo'] = $item['thr-parent'];
1503 $data['inReplyTo'] = null;
1506 $data['diaspora:guid'] = $item['guid'];
1507 $data['published'] = DateTimeFormat::utc($item['created'] . '+00:00', DateTimeFormat::ATOM);
1509 if ($item['created'] != $item['edited']) {
1510 $data['updated'] = DateTimeFormat::utc($item['edited'] . '+00:00', DateTimeFormat::ATOM);
1513 $data['url'] = $item['plink'];
1514 $data['attributedTo'] = $item['author-link'];
1515 $data['sensitive'] = self::isSensitive($item['uri-id']);
1516 $data['context'] = self::fetchContextURLForItem($item);
1518 if (!empty($item['title'])) {
1519 $data['name'] = BBCode::toPlaintext($item['title'], false);
1522 $permission_block = self::createPermissionBlockForItem($item, false);
1524 $body = $item['body'];
1526 if ($type == 'Note') {
1527 $body = $item['raw-body'] ?? self::removePictures($body);
1531 * @todo Improve the automated summary
1532 * This part is currently deactivated. The automated summary seems to be more
1533 * confusing than helping. But possibly we will find a better way.
1534 * So the code is left here for now as a reminder
1536 * } elseif (($type == 'Article') && empty($data['summary'])) {
1537 * $regexp = "/[@!]\[url\=([^\[\]]*)\].*?\[\/url\]/ism";
1538 * $summary = preg_replace_callback($regexp, ['self', 'mentionAddrCallback'], $body);
1539 * $data['summary'] = BBCode::toPlaintext(Plaintext::shorten(self::removePictures($summary), 1000));
1543 if (empty($item['uid']) || !Feature::isEnabled($item['uid'], 'explicit_mentions')) {
1544 $body = self::prependMentions($body, $item['uri-id'], $item['author-link']);
1547 if ($type == 'Event') {
1548 $data = array_merge($data, self::createEvent($item));
1550 $body = BBCode::setMentionsToNicknames($body);
1552 $data['content'] = BBCode::convertForUriId($item['uri-id'], $body, BBCode::ACTIVITYPUB);
1555 // The regular "content" field does contain a minimized HTML. This is done since systems like
1556 // Mastodon has got problems with - for example - embedded pictures.
1557 // The contentMap does contain the unmodified HTML.
1558 $language = self::getLanguage($item);
1559 if (!empty($language)) {
1560 $richbody = BBCode::setMentionsToNicknames($item['body'] ?? '');
1561 $richbody = BBCode::removeAttachment($richbody);
1563 $data['contentMap'][$language] = BBCode::convertForUriId($item['uri-id'], $richbody, BBCode::EXTERNAL);
1566 $data['source'] = ['content' => $item['body'], 'mediaType' => "text/bbcode"];
1568 if (!empty($item['signed_text']) && ($item['uri'] != $item['thr-parent'])) {
1569 $data['diaspora:comment'] = $item['signed_text'];
1572 $data['attachment'] = self::createAttachmentList($item, $type);
1573 $data['tag'] = self::createTagList($item);
1575 if (empty($data['location']) && (!empty($item['coord']) || !empty($item['location']))) {
1576 $data['location'] = self::createLocation($item);
1579 if (!empty($item['app'])) {
1580 $data['generator'] = ['type' => 'Application', 'name' => $item['app']];
1583 $data = array_merge($data, $permission_block);
1589 * Fetches the language from the post, the user or the system.
1591 * @param array $item
1593 * @return string language string
1595 private static function getLanguage(array $item)
1597 // Try to fetch the language from the post itself
1598 if (!empty($item['language'])) {
1599 $languages = array_keys(json_decode($item['language'], true));
1600 if (!empty($languages[0])) {
1601 return $languages[0];
1605 // Otherwise use the user's language
1606 if (!empty($item['uid'])) {
1607 $user = DBA::selectFirst('user', ['language'], ['uid' => $item['uid']]);
1608 if (!empty($user['language'])) {
1609 return $user['language'];
1613 // And finally just use the system language
1614 return DI::config()->get('system', 'language');
1618 * Creates an an "add tag" entry
1620 * @param array $item
1621 * @param array $data activity data
1623 * @return array with activity data for adding tags
1624 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1625 * @throws \ImagickException
1627 private static function createAddTag($item, $data)
1629 $object = XML::parseString($item['object']);
1630 $target = XML::parseString($item["target"]);
1632 $data['diaspora:guid'] = $item['guid'];
1633 $data['actor'] = $item['author-link'];
1634 $data['target'] = (string)$target->id;
1635 $data['summary'] = BBCode::toPlaintext($item['body']);
1636 $data['object'] = ['id' => (string)$object->id, 'type' => 'tag', 'name' => (string)$object->title, 'content' => (string)$object->content];
1642 * Creates an announce object entry
1644 * @param array $item
1645 * @param array $data activity data
1647 * @return array with activity data
1648 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1649 * @throws \ImagickException
1651 private static function createAnnounce($item, $data)
1653 $orig_body = $item['body'];
1654 $announce = self::getAnnounceArray($item);
1655 if (empty($announce)) {
1656 $data['type'] = 'Create';
1657 $data['object'] = self::createNote($item);
1661 if (empty($announce['comment'])) {
1662 // Pure announce, without a quote
1663 $data['type'] = 'Announce';
1664 $data['object'] = $announce['object']['uri'];
1669 $data['type'] = 'Create';
1670 $item['body'] = $announce['comment'] . "\n" . $announce['object']['plink'];
1671 $data['object'] = self::createNote($item);
1673 /// @todo Finally descide how to implement this in AP. This is a possible way:
1674 $data['object']['attachment'][] = self::createNote($announce['object']);
1676 $data['object']['source']['content'] = $orig_body;
1681 * Return announce related data if the item is an annunce
1683 * @param array $item
1687 public static function getAnnounceArray($item)
1689 $reshared = Item::getShareArray($item);
1690 if (empty($reshared['guid'])) {
1694 $reshared_item = Post::selectFirst(Item::DELIVER_FIELDLIST, ['guid' => $reshared['guid']]);
1695 if (!DBA::isResult($reshared_item)) {
1699 if (!in_array($reshared_item['network'], [Protocol::ACTIVITYPUB, Protocol::DFRN])) {
1703 $profile = APContact::getByURL($reshared_item['author-link'], false);
1704 if (empty($profile)) {
1708 return ['object' => $reshared_item, 'actor' => $profile, 'comment' => $reshared['comment']];
1712 * Checks if the provided item array is an announce
1714 * @param array $item
1718 public static function isAnnounce($item)
1720 if (!empty($item['verb']) && ($item['verb'] == Activity::ANNOUNCE)) {
1724 $announce = self::getAnnounceArray($item);
1725 if (empty($announce)) {
1729 return empty($announce['comment']);
1733 * Creates an activity id for a given contact id
1735 * @param integer $cid Contact ID of target
1737 * @return bool|string activity id
1739 public static function activityIDFromContact($cid)
1741 $contact = DBA::selectFirst('contact', ['uid', 'id', 'created'], ['id' => $cid]);
1742 if (!DBA::isResult($contact)) {
1746 $hash = hash('ripemd128', $contact['uid'].'-'.$contact['id'].'-'.$contact['created']);
1747 $uuid = substr($hash, 0, 8). '-' . substr($hash, 8, 4) . '-' . substr($hash, 12, 4) . '-' . substr($hash, 16, 4) . '-' . substr($hash, 20, 12);
1748 return DI::baseUrl() . '/activity/' . $uuid;
1752 * Transmits a contact suggestion to a given inbox
1754 * @param integer $uid User ID
1755 * @param string $inbox Target inbox
1756 * @param integer $suggestion_id Suggestion ID
1758 * @return boolean was the transmission successful?
1759 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1761 public static function sendContactSuggestion($uid, $inbox, $suggestion_id)
1763 $owner = User::getOwnerDataById($uid);
1765 $suggestion = DI::fsuggest()->getById($suggestion_id);
1767 $data = ['@context' => ActivityPub::CONTEXT,
1768 'id' => DI::baseUrl() . '/activity/' . System::createGUID(),
1769 'type' => 'Announce',
1770 'actor' => $owner['url'],
1771 'object' => $suggestion->url,
1772 'content' => $suggestion->note,
1773 'instrument' => self::getService(),
1774 'to' => [ActivityPub::PUBLIC_COLLECTION],
1777 $signed = LDSignature::sign($data, $owner);
1779 Logger::log('Deliver profile deletion for user ' . $uid . ' to ' . $inbox . ' via ActivityPub', Logger::DEBUG);
1780 return HTTPSignature::transmit($signed, $inbox, $uid);
1784 * Transmits a profile relocation to a given inbox
1786 * @param integer $uid User ID
1787 * @param string $inbox Target inbox
1789 * @return boolean was the transmission successful?
1790 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1792 public static function sendProfileRelocation($uid, $inbox)
1794 $owner = User::getOwnerDataById($uid);
1796 $data = ['@context' => ActivityPub::CONTEXT,
1797 'id' => DI::baseUrl() . '/activity/' . System::createGUID(),
1798 'type' => 'dfrn:relocate',
1799 'actor' => $owner['url'],
1800 'object' => $owner['url'],
1801 'published' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
1802 'instrument' => self::getService(),
1803 'to' => [ActivityPub::PUBLIC_COLLECTION],
1806 $signed = LDSignature::sign($data, $owner);
1808 Logger::log('Deliver profile relocation for user ' . $uid . ' to ' . $inbox . ' via ActivityPub', Logger::DEBUG);
1809 return HTTPSignature::transmit($signed, $inbox, $uid);
1813 * Transmits a profile deletion to a given inbox
1815 * @param integer $uid User ID
1816 * @param string $inbox Target inbox
1818 * @return boolean was the transmission successful?
1819 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1821 public static function sendProfileDeletion($uid, $inbox)
1823 $owner = User::getOwnerDataById($uid);
1825 if (empty($owner)) {
1826 Logger::error('No owner data found, the deletion message cannot be processed.', ['user' => $uid]);
1830 if (empty($owner['uprvkey'])) {
1831 Logger::error('No private key for owner found, the deletion message cannot be processed.', ['user' => $uid]);
1835 $data = ['@context' => ActivityPub::CONTEXT,
1836 'id' => DI::baseUrl() . '/activity/' . System::createGUID(),
1838 'actor' => $owner['url'],
1839 'object' => $owner['url'],
1840 'published' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
1841 'instrument' => self::getService(),
1842 'to' => [ActivityPub::PUBLIC_COLLECTION],
1845 $signed = LDSignature::sign($data, $owner);
1847 Logger::log('Deliver profile deletion for user ' . $uid . ' to ' . $inbox . ' via ActivityPub', Logger::DEBUG);
1848 return HTTPSignature::transmit($signed, $inbox, $uid);
1852 * Transmits a profile change to a given inbox
1854 * @param integer $uid User ID
1855 * @param string $inbox Target inbox
1857 * @return boolean was the transmission successful?
1858 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1859 * @throws \ImagickException
1861 public static function sendProfileUpdate($uid, $inbox)
1863 $owner = User::getOwnerDataById($uid);
1864 $profile = APContact::getByURL($owner['url']);
1866 $data = ['@context' => ActivityPub::CONTEXT,
1867 'id' => DI::baseUrl() . '/activity/' . System::createGUID(),
1869 'actor' => $owner['url'],
1870 'object' => self::getProfile($uid),
1871 'published' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
1872 'instrument' => self::getService(),
1873 'to' => [$profile['followers']],
1876 $signed = LDSignature::sign($data, $owner);
1878 Logger::log('Deliver profile update for user ' . $uid . ' to ' . $inbox . ' via ActivityPub', Logger::DEBUG);
1879 return HTTPSignature::transmit($signed, $inbox, $uid);
1883 * Transmits a given activity to a target
1885 * @param string $activity Type name
1886 * @param string $target Target profile
1887 * @param integer $uid User ID
1889 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1890 * @throws \ImagickException
1891 * @throws \Exception
1893 public static function sendActivity($activity, $target, $uid, $id = '')
1895 $profile = APContact::getByURL($target);
1896 if (empty($profile['inbox'])) {
1897 Logger::warning('No inbox found for target', ['target' => $target, 'profile' => $profile]);
1901 $owner = User::getOwnerDataById($uid);
1904 $id = DI::baseUrl() . '/activity/' . System::createGUID();
1907 $data = ['@context' => ActivityPub::CONTEXT,
1909 'type' => $activity,
1910 'actor' => $owner['url'],
1911 'object' => $profile['url'],
1912 'instrument' => self::getService(),
1913 'to' => [$profile['url']]];
1915 Logger::log('Sending activity ' . $activity . ' to ' . $target . ' for user ' . $uid, Logger::DEBUG);
1917 $signed = LDSignature::sign($data, $owner);
1918 return HTTPSignature::transmit($signed, $profile['inbox'], $uid);
1922 * Transmits a "follow object" activity to a target
1923 * This is a preparation for sending automated "follow" requests when receiving "Announce" messages
1925 * @param string $object Object URL
1926 * @param string $target Target profile
1927 * @param integer $uid User ID
1929 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1930 * @throws \ImagickException
1931 * @throws \Exception
1933 public static function sendFollowObject($object, $target, $uid = 0)
1935 $profile = APContact::getByURL($target);
1936 if (empty($profile['inbox'])) {
1937 Logger::warning('No inbox found for target', ['target' => $target, 'profile' => $profile]);
1942 // Fetch the list of administrators
1943 $admin_mail = explode(',', str_replace(' ', '', DI::config()->get('config', 'admin_email')));
1945 // We need to use some user as a sender. It doesn't care who it will send. We will use an administrator account.
1946 $condition = ['verified' => true, 'blocked' => false, 'account_removed' => false, 'account_expired' => false, 'email' => $admin_mail];
1947 $first_user = DBA::selectFirst('user', ['uid'], $condition);
1948 $uid = $first_user['uid'];
1951 $condition = ['verb' => Activity::FOLLOW, 'uid' => 0, 'parent-uri' => $object,
1952 'author-id' => Contact::getPublicIdByUserId($uid)];
1953 if (Post::exists($condition)) {
1954 Logger::log('Follow for ' . $object . ' for user ' . $uid . ' does already exist.', Logger::DEBUG);
1958 $owner = User::getOwnerDataById($uid);
1960 $data = ['@context' => ActivityPub::CONTEXT,
1961 'id' => DI::baseUrl() . '/activity/' . System::createGUID(),
1963 'actor' => $owner['url'],
1964 'object' => $object,
1965 'instrument' => self::getService(),
1966 'to' => [$profile['url']]];
1968 Logger::log('Sending follow ' . $object . ' to ' . $target . ' for user ' . $uid, Logger::DEBUG);
1970 $signed = LDSignature::sign($data, $owner);
1971 return HTTPSignature::transmit($signed, $profile['inbox'], $uid);
1975 * Transmit a message that the contact request had been accepted
1977 * @param string $target Target profile
1979 * @param integer $uid User ID
1980 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1981 * @throws \ImagickException
1983 public static function sendContactAccept($target, $id, $uid)
1985 $profile = APContact::getByURL($target);
1986 if (empty($profile['inbox'])) {
1987 Logger::warning('No inbox found for target', ['target' => $target, 'profile' => $profile]);
1991 $owner = User::getOwnerDataById($uid);
1992 $data = ['@context' => ActivityPub::CONTEXT,
1993 'id' => DI::baseUrl() . '/activity/' . System::createGUID(),
1995 'actor' => $owner['url'],
1997 'id' => (string)$id,
1999 'actor' => $profile['url'],
2000 'object' => $owner['url']
2002 'instrument' => self::getService(),
2003 'to' => [$profile['url']]];
2005 Logger::debug('Sending accept to ' . $target . ' for user ' . $uid . ' with id ' . $id);
2007 $signed = LDSignature::sign($data, $owner);
2008 HTTPSignature::transmit($signed, $profile['inbox'], $uid);
2012 * Reject a contact request or terminates the contact relation
2014 * @param string $target Target profile
2016 * @param integer $uid User ID
2017 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2018 * @throws \ImagickException
2020 public static function sendContactReject($target, $id, $uid)
2022 $profile = APContact::getByURL($target);
2023 if (empty($profile['inbox'])) {
2024 Logger::warning('No inbox found for target', ['target' => $target, 'profile' => $profile]);
2028 $owner = User::getOwnerDataById($uid);
2029 $data = ['@context' => ActivityPub::CONTEXT,
2030 'id' => DI::baseUrl() . '/activity/' . System::createGUID(),
2032 'actor' => $owner['url'],
2034 'id' => (string)$id,
2036 'actor' => $profile['url'],
2037 'object' => $owner['url']
2039 'instrument' => self::getService(),
2040 'to' => [$profile['url']]];
2042 Logger::debug('Sending reject to ' . $target . ' for user ' . $uid . ' with id ' . $id);
2044 $signed = LDSignature::sign($data, $owner);
2045 HTTPSignature::transmit($signed, $profile['inbox'], $uid);
2049 * Transmits a message that we don't want to follow this contact anymore
2051 * @param string $target Target profile
2052 * @param integer $uid User ID
2053 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2054 * @throws \ImagickException
2055 * @throws \Exception
2056 * @return bool success
2058 public static function sendContactUndo($target, $cid, $uid)
2060 $profile = APContact::getByURL($target);
2061 if (empty($profile['inbox'])) {
2062 Logger::warning('No inbox found for target', ['target' => $target, 'profile' => $profile]);
2066 $object_id = self::activityIDFromContact($cid);
2067 if (empty($object_id)) {
2071 $id = DI::baseUrl() . '/activity/' . System::createGUID();
2073 $owner = User::getOwnerDataById($uid);
2074 $data = ['@context' => ActivityPub::CONTEXT,
2077 'actor' => $owner['url'],
2078 'object' => ['id' => $object_id, 'type' => 'Follow',
2079 'actor' => $owner['url'],
2080 'object' => $profile['url']],
2081 'instrument' => self::getService(),
2082 'to' => [$profile['url']]];
2084 Logger::log('Sending undo to ' . $target . ' for user ' . $uid . ' with id ' . $id, Logger::DEBUG);
2086 $signed = LDSignature::sign($data, $owner);
2087 return HTTPSignature::transmit($signed, $profile['inbox'], $uid);
2090 private static function prependMentions($body, int $uriid, string $authorLink)
2094 foreach (Tag::getByURIId($uriid, [Tag::IMPLICIT_MENTION]) as $tag) {
2095 $profile = Contact::getByURL($tag['url'], false, ['addr', 'contact-type', 'nick']);
2096 if (!empty($profile['addr'])
2097 && $profile['contact-type'] != Contact::TYPE_COMMUNITY
2098 && !strstr($body, $profile['addr'])
2099 && !strstr($body, $tag['url'])
2100 && $tag['url'] !== $authorLink
2102 $mentions[] = '@[url=' . $tag['url'] . ']' . $profile['nick'] . '[/url]';
2106 $mentions[] = $body;
2108 return implode(' ', $mentions);