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\Core\Cache\Duration;
27 use Friendica\Core\Logger;
28 use Friendica\Core\Protocol;
29 use Friendica\Core\System;
30 use Friendica\Database\DBA;
32 use Friendica\Model\APContact;
33 use Friendica\Model\Contact;
34 use Friendica\Model\Conversation;
35 use Friendica\Model\GServer;
36 use Friendica\Model\Item;
37 use Friendica\Model\Photo;
38 use Friendica\Model\Post;
39 use Friendica\Model\Profile;
40 use Friendica\Model\Tag;
41 use Friendica\Model\User;
42 use Friendica\Network\HTTPException;
43 use Friendica\Protocol\Activity;
44 use Friendica\Protocol\ActivityPub;
45 use Friendica\Protocol\Relay;
46 use Friendica\Util\DateTimeFormat;
47 use Friendica\Util\HTTPSignature;
48 use Friendica\Util\JsonLD;
49 use Friendica\Util\LDSignature;
50 use Friendica\Util\Map;
51 use Friendica\Util\Network;
52 use Friendica\Util\XML;
55 * ActivityPub Transmitter Protocol class
63 * Add relay servers to the list of inboxes
65 * @param array $inboxes
66 * @return array inboxes with added relay servers
68 public static function addRelayServerInboxes(array $inboxes = [])
70 foreach (Relay::getList(['inbox']) as $contact) {
71 $inboxes[$contact['inbox']] = $contact['inbox'];
78 * Add relay servers to the list of inboxes
80 * @param array $inboxes
81 * @return array inboxes with added relay servers
83 public static function addRelayServerInboxesForItem(int $item_id, array $inboxes = [])
85 $item = Post::selectFirst(['uid'], ['id' => $item_id]);
90 $relays = Relay::getDirectRelayList($item_id);
95 foreach ($relays as $relay) {
96 $contact = Contact::getByURLForUser($relay['url'], $item['uid'], false, ['id']);
97 $inboxes[$relay['batch']][] = $contact['id'] ?? 0;
103 * Subscribe to a relay
105 * @param string $url Subscribe actor url
106 * @return bool success
108 public static function sendRelayFollow(string $url)
110 $contact = Contact::getByURL($url);
111 if (empty($contact)) {
115 $activity_id = ActivityPub\Transmitter::activityIDFromContact($contact['id']);
116 $success = ActivityPub\Transmitter::sendActivity('Follow', $url, 0, $activity_id);
118 DBA::update('contact', ['rel' => Contact::FRIEND], ['id' => $contact['id']]);
125 * Unsubscribe from a relay
127 * @param string $url Subscribe actor url
128 * @param bool $force Set the relay status as non follower even if unsubscribe hadn't worked
129 * @return bool success
131 public static function sendRelayUndoFollow(string $url, bool $force = false)
133 $contact = Contact::getByURL($url);
134 if (empty($contact)) {
138 $success = self::sendContactUndo($url, $contact['id'], 0);
139 if ($success || $force) {
140 DBA::update('contact', ['rel' => Contact::NOTHING], ['id' => $contact['id']]);
147 * Collects a list of contacts of the given owner
149 * @param array $owner Owner array
150 * @param int|array $rel The relevant value(s) contact.rel should match
151 * @param string $module The name of the relevant AP endpoint module (followers|following)
152 * @param integer $page Page number
154 * @return array of owners
157 public static function getContacts($owner, $rel, $module, $page = null)
161 'uid' => $owner['uid'],
169 $condition = DBA::buildCondition($parameters);
171 $sql = "SELECT COUNT(*) as `count`
173 JOIN `apcontact` ON `apcontact`.`url` = `contact`.`url`
176 $contacts = DBA::fetchFirst($sql, ...$parameters);
178 $modulePath = '/' . $module . '/';
180 $data = ['@context' => ActivityPub::CONTEXT];
181 $data['id'] = DI::baseUrl() . $modulePath . $owner['nickname'];
182 $data['type'] = 'OrderedCollection';
183 $data['totalItems'] = $contacts['count'];
185 // When we hide our friends we will only show the pure number but don't allow more.
186 $profile = Profile::getByUID($owner['uid']);
187 if (!empty($profile['hide-friends'])) {
192 $data['first'] = DI::baseUrl() . $modulePath . $owner['nickname'] . '?page=1';
194 $data['type'] = 'OrderedCollectionPage';
197 $sql = "SELECT `contact`.`url`
199 JOIN `apcontact` ON `apcontact`.`url` = `contact`.`url`
203 $parameters[] = ($page - 1) * 100;
206 $contacts = DBA::p($sql, ...$parameters);
207 while ($contact = DBA::fetch($contacts)) {
208 $list[] = $contact['url'];
210 DBA::close($contacts);
213 $data['next'] = DI::baseUrl() . $modulePath . $owner['nickname'] . '?page=' . ($page + 1);
216 $data['partOf'] = DI::baseUrl() . $modulePath . $owner['nickname'];
218 $data['orderedItems'] = $list;
225 * Public posts for the given owner
227 * @param array $owner Owner array
228 * @param integer $page Page number
229 * @param string $requester URL of requesting account
231 * @return array of posts
232 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
233 * @throws \ImagickException
235 public static function getOutbox($owner, $page = null, $requester = '')
237 $condition = ['private' => [Item::PUBLIC, Item::UNLISTED]];
239 if (!empty($requester)) {
240 $requester_id = Contact::getIdForURL($requester, $owner['uid']);
241 if (!empty($requester_id)) {
242 $permissionSets = DI::permissionSet()->selectByContactId($requester_id, $owner['uid']);
243 if (!empty($permissionSets)) {
244 $condition = ['psid' => array_merge($permissionSets->column('id'),
245 [DI::permissionSet()->getIdFromACL($owner['uid'], '', '', '', '')])];
250 $condition = array_merge($condition,
251 ['uid' => $owner['uid'],
252 'author-id' => Contact::getIdForURL($owner['url'], 0, false),
253 'gravity' => [GRAVITY_PARENT, GRAVITY_COMMENT],
254 'network' => Protocol::FEDERATED,
255 'parent-network' => Protocol::FEDERATED,
260 $count = Post::count($condition);
262 $data = ['@context' => ActivityPub::CONTEXT];
263 $data['id'] = DI::baseUrl() . '/outbox/' . $owner['nickname'];
264 $data['type'] = 'OrderedCollection';
265 $data['totalItems'] = $count;
268 $data['first'] = DI::baseUrl() . '/outbox/' . $owner['nickname'] . '?page=1';
270 $data['type'] = 'OrderedCollectionPage';
273 $items = Post::select(['id'], $condition, ['limit' => [($page - 1) * 20, 20], 'order' => ['created' => true]]);
274 while ($item = Post::fetch($items)) {
275 $activity = self::createActivityFromItem($item['id'], true);
276 $activity['type'] = $activity['type'] == 'Update' ? 'Create' : $activity['type'];
278 // Only list "Create" activity objects here, no reshares
279 if (!empty($activity['object']) && ($activity['type'] == 'Create')) {
280 $list[] = $activity['object'];
286 $data['next'] = DI::baseUrl() . '/outbox/' . $owner['nickname'] . '?page=' . ($page + 1);
289 $data['partOf'] = DI::baseUrl() . '/outbox/' . $owner['nickname'];
291 $data['orderedItems'] = $list;
298 * Return the service array containing information the used software and it's url
300 * @return array with service data
302 private static function getService()
304 return ['type' => 'Service',
305 'name' => FRIENDICA_PLATFORM . " '" . FRIENDICA_CODENAME . "' " . FRIENDICA_VERSION . '-' . DB_UPDATE_VERSION,
306 'url' => DI::baseUrl()->get()];
310 * Return the ActivityPub profile of the given user
312 * @param int $uid User ID
313 * @return array with profile data
314 * @throws HTTPException\NotFoundException
315 * @throws HTTPException\InternalServerErrorException
317 public static function getProfile(int $uid): array
319 $owner = User::getOwnerDataById($uid);
320 if (!isset($owner['id'])) {
321 DI::logger()->error('Unable to find owner data for uid', ['uid' => $uid, 'callstack' => System::callstack(20)]);
322 throw new HTTPException\NotFoundException('User not found.');
325 $data = ['@context' => ActivityPub::CONTEXT];
326 $data['id'] = $owner['url'];
328 if (!empty($owner['guid'])) {
329 $data['diaspora:guid'] = $owner['guid'];
332 $data['type'] = ActivityPub::ACCOUNT_TYPES[$owner['account-type']];
335 $data['following'] = DI::baseUrl() . '/following/' . $owner['nick'];
336 $data['followers'] = DI::baseUrl() . '/followers/' . $owner['nick'];
337 $data['inbox'] = DI::baseUrl() . '/inbox/' . $owner['nick'];
338 $data['outbox'] = DI::baseUrl() . '/outbox/' . $owner['nick'];
340 $data['inbox'] = DI::baseUrl() . '/friendica/inbox';
343 $data['preferredUsername'] = $owner['nick'];
344 $data['name'] = $owner['name'];
346 if (!empty($owner['country-name'] . $owner['region'] . $owner['locality'])) {
347 $data['vcard:hasAddress'] = ['@type' => 'vcard:Home', 'vcard:country-name' => $owner['country-name'],
348 'vcard:region' => $owner['region'], 'vcard:locality' => $owner['locality']];
351 if (!empty($owner['about'])) {
352 $data['summary'] = BBCode::convertForUriId($owner['uri-id'] ?? 0, $owner['about'], BBCode::EXTERNAL);
355 if (!empty($owner['xmpp']) || !empty($owner['matrix'])) {
356 $data['vcard:hasInstantMessage'] = [];
358 if (!empty($owner['xmpp'])) {
359 $data['vcard:hasInstantMessage'][] = 'xmpp:' . $owner['xmpp'];
361 if (!empty($owner['matrix'])) {
362 $data['vcard:hasInstantMessage'][] = 'matrix:' . $owner['matrix'];
366 $data['url'] = $owner['url'];
367 $data['manuallyApprovesFollowers'] = in_array($owner['page-flags'], [User::PAGE_FLAGS_NORMAL, User::PAGE_FLAGS_PRVGROUP]);
368 $data['discoverable'] = (bool)$owner['net-publish'];
369 $data['publicKey'] = ['id' => $owner['url'] . '#main-key',
370 'owner' => $owner['url'],
371 'publicKeyPem' => $owner['pubkey']];
372 $data['endpoints'] = ['sharedInbox' => DI::baseUrl() . '/inbox'];
373 $data['icon'] = ['type' => 'Image', 'url' => Contact::getAvatarUrlForId($owner['id'], '', $owner['updated'])];
375 $resourceid = Photo::ridFromURI($owner['photo']);
376 if (!empty($resourceid)) {
377 $photo = Photo::selectFirst(['type'], ["resource-id" => $resourceid]);
378 if (!empty($photo['type'])) {
379 $data['icon']['mediaType'] = $photo['type'];
383 if (!empty($owner['header'])) {
384 $data['image'] = ['type' => 'Image', 'url' => Contact::getHeaderUrlForId($owner['id'], '', $owner['updated'])];
386 $resourceid = Photo::ridFromURI($owner['header']);
387 if (!empty($resourceid)) {
388 $photo = Photo::selectFirst(['type'], ["resource-id" => $resourceid]);
389 if (!empty($photo['type'])) {
390 $data['image']['mediaType'] = $photo['type'];
395 $data['generator'] = self::getService();
397 // tags: https://kitty.town/@inmysocks/100656097926961126.json
402 * @param string $username
404 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
406 public static function getDeletedUser($username)
409 '@context' => ActivityPub::CONTEXT,
410 'id' => DI::baseUrl() . '/profile/' . $username,
411 'type' => 'Tombstone',
412 'published' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
413 'updated' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
414 'deleted' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
419 * Returns an array with permissions of a given item array
423 * @return array with permissions
424 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
425 * @throws \ImagickException
427 private static function fetchPermissionBlockFromConversation($item)
429 if (empty($item['thr-parent'])) {
433 $condition = ['item-uri' => $item['thr-parent'], 'protocol' => Conversation::PARCEL_ACTIVITYPUB];
434 $conversation = DBA::selectFirst('conversation', ['source'], $condition);
435 if (!DBA::isResult($conversation)) {
439 $activity = json_decode($conversation['source'], true);
441 $actor = JsonLD::fetchElement($activity, 'actor', 'id');
442 if (!empty($actor)) {
443 $permissions['to'][] = $actor;
444 $profile = APContact::getByURL($actor);
449 $item_profile = APContact::getByURL($item['author-link']);
450 $exclude[] = $item['author-link'];
452 if ($item['gravity'] == GRAVITY_PARENT) {
453 $exclude[] = $item['owner-link'];
456 foreach (['to', 'cc', 'bto', 'bcc'] as $element) {
457 if (empty($activity[$element])) {
460 if (is_string($activity[$element])) {
461 $activity[$element] = [$activity[$element]];
464 foreach ($activity[$element] as $receiver) {
465 if (empty($receiver)) {
469 if (!empty($profile['followers']) && $receiver == $profile['followers'] && !empty($item_profile['followers'])) {
470 $permissions[$element][] = $item_profile['followers'];
471 } elseif (!in_array($receiver, $exclude)) {
472 $permissions[$element][] = $receiver;
480 * Check if the given item id is from ActivityPub
482 * @param integer $item_id
483 * @return boolean "true" if the post is from ActivityPub
485 private static function isAPPost(int $item_id)
487 if (empty($item_id)) {
491 return Post::exists(['id' => $item_id, 'network' => Protocol::ACTIVITYPUB]);
495 * Creates an array of permissions from an item thread
497 * @param array $item Item array
498 * @param boolean $blindcopy addressing via "bcc" or "cc"?
499 * @param integer $last_id Last item id for adding receivers
500 * @param boolean $forum_mode "true" means that we are sending content to a forum
502 * @return array with permission data
503 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
504 * @throws \ImagickException
506 private static function createPermissionBlockForItem($item, $blindcopy, $last_id = 0, $forum_mode = false)
509 $last_id = $item['id'];
514 // Check if we should always deliver our stuff via BCC
515 if (!empty($item['uid'])) {
516 $profile = User::getOwnerDataById($item['uid']);
517 if (!empty($profile)) {
518 $always_bcc = $profile['hide-friends'];
522 if (DI::config()->get('system', 'ap_always_bcc')) {
526 if (self::isAnnounce($item) || DI::config()->get('debug', 'total_ap_delivery') || self::isAPPost($last_id)) {
527 // Will be activated in a later step
528 $networks = Protocol::FEDERATED;
530 // For now only send to these contacts:
531 $networks = [Protocol::ACTIVITYPUB, Protocol::OSTATUS];
534 $data = ['to' => [], 'cc' => [], 'bcc' => []];
536 if ($item['gravity'] == GRAVITY_PARENT) {
537 $actor_profile = APContact::getByURL($item['owner-link']);
539 $actor_profile = APContact::getByURL($item['author-link']);
544 $terms = Tag::getByURIId($item['uri-id'], [Tag::MENTION, Tag::IMPLICIT_MENTION, Tag::EXCLUSIVE_MENTION]);
546 if ($item['private'] != Item::PRIVATE) {
547 // Directly mention the original author upon a quoted reshare.
548 // Else just ensure that the original author receives the reshare.
549 $announce = self::getAnnounceArray($item);
550 if (!empty($announce['comment'])) {
551 $data['to'][] = $announce['actor']['url'];
552 } elseif (!empty($announce)) {
553 $data['cc'][] = $announce['actor']['url'];
556 $data = array_merge($data, self::fetchPermissionBlockFromConversation($item));
558 // Check if the item is completely public or unlisted
559 if ($item['private'] == Item::PUBLIC) {
560 $data['to'][] = ActivityPub::PUBLIC_COLLECTION;
562 $data['cc'][] = ActivityPub::PUBLIC_COLLECTION;
565 foreach ($terms as $term) {
566 $profile = APContact::getByURL($term['url'], false);
567 if (!empty($profile)) {
568 if ($term['type'] == Tag::EXCLUSIVE_MENTION) {
570 if (!empty($profile['followers']) && ($profile['type'] == 'Group')) {
571 $data['cc'][] = $profile['followers'];
574 $data['to'][] = $profile['url'];
578 $receiver_list = Item::enumeratePermissions($item, true);
580 foreach ($terms as $term) {
581 $cid = Contact::getIdForURL($term['url'], $item['uid']);
582 if (!empty($cid) && in_array($cid, $receiver_list)) {
583 $contact = DBA::selectFirst('contact', ['url', 'network', 'protocol', 'gsid'], ['id' => $cid, 'network' => Protocol::FEDERATED]);
584 if (!DBA::isResult($contact) || !self::isAPContact($contact, $networks)) {
588 if (!empty($profile = APContact::getByURL($contact['url'], false))) {
589 $data['to'][] = $profile['url'];
594 foreach ($receiver_list as $receiver) {
595 $contact = DBA::selectFirst('contact', ['url', 'hidden', 'network', 'protocol', 'gsid'], ['id' => $receiver, 'network' => Protocol::FEDERATED]);
596 if (!DBA::isResult($contact) || !self::isAPContact($contact, $networks)) {
600 if (!empty($profile = APContact::getByURL($contact['url'], false))) {
601 if ($contact['hidden'] || $always_bcc) {
602 $data['bcc'][] = $profile['url'];
604 $data['cc'][] = $profile['url'];
610 if (!empty($item['parent'])) {
611 $parents = Post::select(['id', 'author-link', 'owner-link', 'gravity', 'uri'], ['parent' => $item['parent']]);
612 while ($parent = Post::fetch($parents)) {
613 if ($parent['gravity'] == GRAVITY_PARENT) {
614 $profile = APContact::getByURL($parent['owner-link'], false);
615 if (!empty($profile)) {
616 if ($item['gravity'] != GRAVITY_PARENT) {
617 // Comments to forums are directed to the forum
618 // But comments to forums aren't directed to the followers collection
619 // This rule is only valid when the actor isn't the forum.
620 // The forum needs to transmit their content to their followers.
621 if (($profile['type'] == 'Group') && ($profile['url'] != ($actor_profile['url'] ?? ''))) {
622 $data['to'][] = $profile['url'];
624 $data['cc'][] = $profile['url'];
625 if (($item['private'] != Item::PRIVATE) && !empty($actor_profile['followers'])) {
626 $data['cc'][] = $actor_profile['followers'];
629 } elseif (!$exclusive) {
630 // Public thread parent post always are directed to the followers.
631 // This mustn't be done by posts that are directed to forum servers via the exclusive mention.
632 // But possibly in that case we could add the "followers" collection of the forum to the message.
633 if (($item['private'] != Item::PRIVATE) && !$forum_mode) {
634 $data['cc'][] = $actor_profile['followers'];
640 // Don't include data from future posts
641 if ($parent['id'] >= $last_id) {
645 $profile = APContact::getByURL($parent['author-link'], false);
646 if (!empty($profile)) {
647 if (($profile['type'] == 'Group') || ($parent['uri'] == $item['thr-parent'])) {
648 $data['to'][] = $profile['url'];
650 $data['cc'][] = $profile['url'];
654 DBA::close($parents);
657 $data['to'] = array_unique($data['to']);
658 $data['cc'] = array_unique($data['cc']);
659 $data['bcc'] = array_unique($data['bcc']);
661 if (($key = array_search($item['author-link'], $data['to'])) !== false) {
662 unset($data['to'][$key]);
665 if (($key = array_search($item['author-link'], $data['cc'])) !== false) {
666 unset($data['cc'][$key]);
669 if (($key = array_search($item['author-link'], $data['bcc'])) !== false) {
670 unset($data['bcc'][$key]);
673 foreach ($data['to'] as $to) {
674 if (($key = array_search($to, $data['cc'])) !== false) {
675 unset($data['cc'][$key]);
678 if (($key = array_search($to, $data['bcc'])) !== false) {
679 unset($data['bcc'][$key]);
683 foreach ($data['cc'] as $cc) {
684 if (($key = array_search($cc, $data['bcc'])) !== false) {
685 unset($data['bcc'][$key]);
689 $receivers = ['to' => array_values($data['to']), 'cc' => array_values($data['cc']), 'bcc' => array_values($data['bcc'])];
692 unset($receivers['bcc']);
699 * Check if an inbox is archived
701 * @param string $url Inbox url
703 * @return boolean "true" if inbox is archived
705 public static function archivedInbox($url)
707 return DBA::exists('inbox-status', ['url' => $url, 'archive' => true]);
711 * Check if a given contact should be delivered via AP
713 * @param array $contact
714 * @param array $networks
718 private static function isAPContact(array $contact, array $networks)
720 if (in_array($contact['network'], $networks) || ($contact['protocol'] == Protocol::ACTIVITYPUB)) {
724 return GServer::getProtocol($contact['gsid'] ?? 0) == Post\DeliveryData::ACTIVITYPUB;
728 * Fetches a list of inboxes of followers of a given user
730 * @param integer $uid User ID
731 * @param boolean $personal fetch personal inboxes
732 * @param boolean $all_ap Retrieve all AP enabled inboxes
734 * @return array of follower inboxes
735 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
736 * @throws \ImagickException
738 public static function fetchTargetInboxesforUser($uid, $personal = false, bool $all_ap = false)
744 if (!empty($item['uid'])) {
745 $profile = User::getOwnerDataById($item['uid']);
746 if (!empty($profile)) {
747 $isforum = $profile['account-type'] == User::ACCOUNT_TYPE_COMMUNITY;
751 if (DI::config()->get('debug', 'total_ap_delivery') || $all_ap) {
752 // Will be activated in a later step
753 $networks = Protocol::FEDERATED;
755 // For now only send to these contacts:
756 $networks = [Protocol::ACTIVITYPUB, Protocol::OSTATUS];
759 $condition = ['uid' => $uid, 'archive' => false, 'pending' => false, 'blocked' => false, 'network' => Protocol::FEDERATED];
762 $condition['rel'] = [Contact::FOLLOWER, Contact::FRIEND];
765 $contacts = DBA::select('contact', ['id', 'url', 'network', 'protocol', 'gsid'], $condition);
766 while ($contact = DBA::fetch($contacts)) {
767 if (!self::isAPContact($contact, $networks)) {
771 if ($isforum && ($contact['network'] == Protocol::DFRN)) {
775 if (Network::isUrlBlocked($contact['url'])) {
779 $profile = APContact::getByURL($contact['url'], false);
780 if (!empty($profile)) {
781 if (empty($profile['sharedinbox']) || $personal || Contact::isLocal($contact['url'])) {
782 $target = $profile['inbox'];
784 $target = $profile['sharedinbox'];
786 if (!self::archivedInbox($target)) {
787 $inboxes[$target][] = $contact['id'];
791 DBA::close($contacts);
797 * Fetches an array of inboxes for the given item and user
799 * @param array $item Item array
800 * @param integer $uid User ID
801 * @param boolean $personal fetch personal inboxes
802 * @param integer $last_id Last item id for adding receivers
803 * @param boolean $forum_mode "true" means that we are sending content to a forum
804 * @return array with inboxes
805 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
806 * @throws \ImagickException
808 public static function fetchTargetInboxes($item, $uid, $personal = false, $last_id = 0, $forum_mode = false)
810 $permissions = self::createPermissionBlockForItem($item, true, $last_id, $forum_mode);
811 if (empty($permissions)) {
817 if ($item['gravity'] == GRAVITY_ACTIVITY) {
818 $item_profile = APContact::getByURL($item['author-link'], false);
820 $item_profile = APContact::getByURL($item['owner-link'], false);
823 if (empty($item_profile)) {
827 $profile_uid = User::getIdForURL($item_profile['url']);
829 foreach (['to', 'cc', 'bto', 'bcc'] as $element) {
830 if (empty($permissions[$element])) {
834 $blindcopy = in_array($element, ['bto', 'bcc']);
836 foreach ($permissions[$element] as $receiver) {
837 if (empty($receiver) || Network::isUrlBlocked($receiver)) {
841 if ($item_profile && ($receiver == $item_profile['followers']) && ($uid == $profile_uid)) {
842 $inboxes = array_merge($inboxes, self::fetchTargetInboxesforUser($uid, $personal, self::isAPPost($last_id)));
844 $profile = APContact::getByURL($receiver, false);
845 if (!empty($profile)) {
846 $contact = Contact::getByURLForUser($receiver, $uid, false, ['id']);
848 if (empty($profile['sharedinbox']) || $personal || $blindcopy || Contact::isLocal($receiver)) {
849 $target = $profile['inbox'];
851 $target = $profile['sharedinbox'];
853 if (!self::archivedInbox($target)) {
854 $inboxes[$target][] = $contact['id'] ?? 0;
865 * Creates an array in the structure of the item table for a given mail id
867 * @param integer $mail_id
872 public static function ItemArrayFromMail($mail_id, $use_title = false)
874 $mail = DBA::selectFirst('mail', [], ['id' => $mail_id]);
875 if (!DBA::isResult($mail)) {
879 $reply = DBA::selectFirst('mail', ['uri', 'uri-id', 'from-url'], ['parent-uri' => $mail['parent-uri'], 'reply' => false]);
881 // Making the post more compatible for Mastodon by:
882 // - Making it a note and not an article (no title)
883 // - Moving the title into the "summary" field that is used as a "content warning"
886 $mail['body'] = '[abstract]' . $mail['title'] . "[/abstract]\n" . $mail['body'];
890 $mail['author-link'] = $mail['owner-link'] = $mail['from-url'];
891 $mail['owner-id'] = $mail['author-id'];
892 $mail['allow_cid'] = '<'.$mail['contact-id'].'>';
893 $mail['allow_gid'] = '';
894 $mail['deny_cid'] = '';
895 $mail['deny_gid'] = '';
896 $mail['private'] = Item::PRIVATE;
897 $mail['deleted'] = false;
898 $mail['edited'] = $mail['created'];
899 $mail['plink'] = DI::baseUrl() . '/message/' . $mail['id'];
900 $mail['parent-uri'] = $reply['uri'];
901 $mail['parent-uri-id'] = $reply['uri-id'];
902 $mail['parent-author-id'] = Contact::getIdForURL($reply['from-url'], 0, false);
903 $mail['gravity'] = ($mail['reply'] ? GRAVITY_COMMENT: GRAVITY_PARENT);
904 $mail['event-type'] = '';
905 $mail['language'] = '';
912 * Creates an activity array for a given mail id
914 * @param integer $mail_id
915 * @param boolean $object_mode Is the activity item is used inside another object?
917 * @return array of activity
920 public static function createActivityFromMail($mail_id, $object_mode = false)
922 $mail = self::ItemArrayFromMail($mail_id);
926 $object = self::createNote($mail);
929 $data = ['@context' => ActivityPub::CONTEXT];
934 $data['id'] = $mail['uri'] . '/Create';
935 $data['type'] = 'Create';
936 $data['actor'] = $mail['author-link'];
937 $data['published'] = DateTimeFormat::utc($mail['created'] . '+00:00', DateTimeFormat::ATOM);
938 $data['instrument'] = self::getService();
939 $data = array_merge($data, self::createPermissionBlockForItem($mail, true));
941 if (empty($data['to']) && !empty($data['cc'])) {
942 $data['to'] = $data['cc'];
945 if (empty($data['to']) && !empty($data['bcc'])) {
946 $data['to'] = $data['bcc'];
952 $object['to'] = $data['to'];
953 $object['tag'] = [['type' => 'Mention', 'href' => $object['to'][0], 'name' => '']];
955 unset($object['cc']);
956 unset($object['bcc']);
958 $data['directMessage'] = true;
960 $data['object'] = $object;
962 $owner = User::getOwnerDataById($mail['uid']);
964 if (!$object_mode && !empty($owner)) {
965 return LDSignature::sign($data, $owner);
972 * Returns the activity type of a given item
976 * @return string with activity type
977 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
978 * @throws \ImagickException
980 private static function getTypeOfItem($item)
984 // Only check for a reshare, if it is a real reshare and no quoted reshare
985 if (strpos($item['body'], "[share") === 0) {
986 $announce = self::getAnnounceArray($item);
987 $reshared = !empty($announce);
992 } elseif ($item['verb'] == Activity::POST) {
993 if ($item['created'] == $item['edited']) {
998 } elseif ($item['verb'] == Activity::LIKE) {
1000 } elseif ($item['verb'] == Activity::DISLIKE) {
1002 } elseif ($item['verb'] == Activity::ATTEND) {
1004 } elseif ($item['verb'] == Activity::ATTENDNO) {
1006 } elseif ($item['verb'] == Activity::ATTENDMAYBE) {
1007 $type = 'TentativeAccept';
1008 } elseif ($item['verb'] == Activity::FOLLOW) {
1010 } elseif ($item['verb'] == Activity::TAG) {
1012 } elseif ($item['verb'] == Activity::ANNOUNCE) {
1022 * Creates the activity or fetches it from the cache
1024 * @param integer $item_id
1025 * @param boolean $force Force new cache entry
1027 * @return array with the activity
1028 * @throws \Exception
1030 public static function createCachedActivityFromItem($item_id, $force = false)
1032 $cachekey = 'APDelivery:createActivity:' . $item_id;
1035 $data = DI::cache()->get($cachekey);
1036 if (!is_null($data)) {
1041 $data = self::createActivityFromItem($item_id);
1043 DI::cache()->set($cachekey, $data, Duration::QUARTER_HOUR);
1048 * Creates an activity array for a given item id
1050 * @param integer $item_id
1051 * @param boolean $object_mode Is the activity item is used inside another object?
1053 * @return false|array
1054 * @throws \Exception
1056 public static function createActivityFromItem(int $item_id, bool $object_mode = false)
1058 Logger::info('Fetching activity', ['item' => $item_id]);
1059 $item = Post::selectFirst(Item::DELIVER_FIELDLIST, ['id' => $item_id, 'parent-network' => Protocol::NATIVE_SUPPORT]);
1060 if (!DBA::isResult($item)) {
1064 // In case of a forum post ensure to return the original post if author and forum are on the same machine
1065 if (($item['gravity'] == GRAVITY_PARENT) && !empty($item['forum_mode'])) {
1066 $author = Contact::getById($item['author-id'], ['nurl']);
1067 if (!empty($author['nurl'])) {
1068 $self = Contact::selectFirst(['uid'], ['nurl' => $author['nurl'], 'self' => true]);
1069 if (!empty($self['uid'])) {
1070 $forum_item = Post::selectFirst(Item::DELIVER_FIELDLIST, ['uri-id' => $item['uri-id'], 'uid' => $self['uid']]);
1071 if (DBA::isResult($forum_item)) {
1072 $item = $forum_item;
1078 if (empty($item['uri-id'])) {
1079 Logger::warning('Item without uri-id', ['item' => $item]);
1083 if (!$item['deleted']) {
1084 $condition = ['item-uri' => $item['uri'], 'protocol' => Conversation::PARCEL_ACTIVITYPUB];
1085 $conversation = DBA::selectFirst('conversation', ['source'], $condition);
1086 if (!$item['origin'] && DBA::isResult($conversation)) {
1087 $data = json_decode($conversation['source'], true);
1088 if (!empty($data['type'])) {
1089 if (in_array($data['type'], ['Create', 'Update'])) {
1091 unset($data['@context']);
1092 unset($data['signature']);
1094 Logger::info('Return stored conversation', ['item' => $item_id]);
1096 } elseif (in_array('as:' . $data['type'], Receiver::CONTENT_TYPES)) {
1097 if (!empty($data['@context'])) {
1098 $context = $data['@context'];
1099 unset($data['@context']);
1101 unset($data['actor']);
1108 $type = self::getTypeOfItem($item);
1110 if (!$object_mode) {
1111 $data = ['@context' => $context ?? ActivityPub::CONTEXT];
1113 if ($item['deleted'] && ($item['gravity'] == GRAVITY_ACTIVITY)) {
1115 } elseif ($item['deleted']) {
1122 if ($type == 'Delete') {
1123 $data['id'] = Item::newURI($item['uid'], $item['guid']) . '/' . $type;;
1124 } elseif (($item['gravity'] == GRAVITY_ACTIVITY) && ($type != 'Undo')) {
1125 $data['id'] = $item['uri'];
1127 $data['id'] = $item['uri'] . '/' . $type;
1130 $data['type'] = $type;
1132 if (($type != 'Announce') || ($item['gravity'] != GRAVITY_PARENT)) {
1133 $data['actor'] = $item['author-link'];
1135 $data['actor'] = $item['owner-link'];
1138 $data['published'] = DateTimeFormat::utc($item['created'] . '+00:00', DateTimeFormat::ATOM);
1140 $data['instrument'] = self::getService();
1142 $data = array_merge($data, self::createPermissionBlockForItem($item, false));
1144 if (in_array($data['type'], ['Create', 'Update', 'Delete'])) {
1145 $data['object'] = $object ?? self::createNote($item);
1146 } elseif ($data['type'] == 'Add') {
1147 $data = self::createAddTag($item, $data);
1148 } elseif ($data['type'] == 'Announce') {
1149 if ($item['verb'] == ACTIVITY::ANNOUNCE) {
1150 $data['object'] = $item['thr-parent'];
1152 $data = self::createAnnounce($item, $data);
1154 } elseif ($data['type'] == 'Follow') {
1155 $data['object'] = $item['parent-uri'];
1156 } elseif ($data['type'] == 'Undo') {
1157 $data['object'] = self::createActivityFromItem($item_id, true);
1159 $data['diaspora:guid'] = $item['guid'];
1160 if (!empty($item['signed_text'])) {
1161 $data['diaspora:like'] = $item['signed_text'];
1163 $data['object'] = $item['thr-parent'];
1166 if (!empty($item['contact-uid'])) {
1167 $uid = $item['contact-uid'];
1169 $uid = $item['uid'];
1172 $owner = User::getOwnerDataById($uid);
1174 Logger::info('Fetched activity', ['item' => $item_id, 'uid' => $uid]);
1176 // We don't sign if we aren't the actor. This is important for relaying content especially for forums
1177 if (!$object_mode && !empty($owner) && ($data['actor'] == $owner['url'])) {
1178 return LDSignature::sign($data, $owner);
1183 /// @todo Create "conversation" entry
1187 * Creates a location entry for a given item array
1189 * @param array $item
1191 * @return array with location array
1193 private static function createLocation($item)
1195 $location = ['type' => 'Place'];
1197 if (!empty($item['location'])) {
1198 $location['name'] = $item['location'];
1203 if (empty($item['coord'])) {
1204 $coord = Map::getCoordinates($item['location']);
1206 $coords = explode(' ', $item['coord']);
1207 if (count($coords) == 2) {
1208 $coord = ['lat' => $coords[0], 'lon' => $coords[1]];
1212 if (!empty($coord['lat']) && !empty($coord['lon'])) {
1213 $location['latitude'] = $coord['lat'];
1214 $location['longitude'] = $coord['lon'];
1221 * Returns a tag array for a given item array
1223 * @param array $item
1225 * @return array of tags
1226 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1228 private static function createTagList($item)
1232 $terms = Tag::getByURIId($item['uri-id'], [Tag::HASHTAG, Tag::MENTION, Tag::IMPLICIT_MENTION, Tag::EXCLUSIVE_MENTION]);
1233 foreach ($terms as $term) {
1234 if ($term['type'] == Tag::HASHTAG) {
1235 $url = DI::baseUrl() . '/search?tag=' . urlencode($term['name']);
1236 $tags[] = ['type' => 'Hashtag', 'href' => $url, 'name' => '#' . $term['name']];
1238 $contact = Contact::getByURL($term['url'], false, ['addr']);
1239 if (empty($contact)) {
1242 if (!empty($contact['addr'])) {
1243 $mention = '@' . $contact['addr'];
1245 $mention = '@' . $term['url'];
1248 $tags[] = ['type' => 'Mention', 'href' => $term['url'], 'name' => $mention];
1252 $announce = self::getAnnounceArray($item);
1253 // Mention the original author upon commented reshares
1254 if (!empty($announce['comment'])) {
1255 $tags[] = ['type' => 'Mention', 'href' => $announce['actor']['url'], 'name' => '@' . $announce['actor']['addr']];
1262 * Adds attachment data to the JSON document
1264 * @param array $item Data of the item that is to be posted
1265 * @param string $type Object type
1267 * @return array with attachment data
1268 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1270 private static function createAttachmentList($item, $type)
1274 $uriids = [$item['uri-id']];
1275 $shared = BBCode::fetchShareAttributes($item['body']);
1276 if (!empty($shared['guid'])) {
1277 $shared_item = Post::selectFirst(['uri-id'], ['guid' => $shared['guid']]);
1278 if (!empty($shared_item['uri-id'])) {
1279 $uriids[] = $shared_item['uri-id'];
1284 foreach ($uriids as $uriid) {
1285 foreach (Post\Media::getByURIId($uriid, [Post\Media::DOCUMENT, Post\Media::TORRENT]) as $attachment) {
1286 if (in_array($attachment['url'], $urls)) {
1289 $urls[] = $attachment['url'];
1291 $attach = ['type' => 'Document',
1292 'mediaType' => $attachment['mimetype'],
1293 'url' => $attachment['url'],
1294 'name' => $attachment['description']];
1296 if (!empty($attachment['height'])) {
1297 $attach['height'] = $attachment['height'];
1300 if (!empty($attachment['width'])) {
1301 $attach['width'] = $attachment['width'];
1304 if (!empty($attachment['preview'])) {
1305 $attach['image'] = $attachment['preview'];
1308 $attachments[] = $attach;
1312 if ($type != 'Note') {
1313 return $attachments;
1316 foreach ($uriids as $uriid) {
1317 foreach (Post\Media::getByURIId($uriid, [Post\Media::AUDIO, Post\Media::IMAGE, Post\Media::VIDEO]) as $attachment) {
1318 if (in_array($attachment['url'], $urls)) {
1321 $urls[] = $attachment['url'];
1323 $attach = ['type' => 'Document',
1324 'mediaType' => $attachment['mimetype'],
1325 'url' => $attachment['url'],
1326 'name' => $attachment['description']];
1328 if (!empty($attachment['height'])) {
1329 $attach['height'] = $attachment['height'];
1332 if (!empty($attachment['width'])) {
1333 $attach['width'] = $attachment['width'];
1336 if (!empty($attachment['preview'])) {
1337 $attach['image'] = $attachment['preview'];
1340 $attachments[] = $attach;
1342 // Currently deactivated, since it creates side effects on Mastodon and Pleroma.
1343 // It will be activated, once this cleared.
1345 foreach (Post\Media::getByURIId($uriid, [Post\Media::HTML]) as $attachment) {
1346 if (in_array($attachment['url'], $urls)) {
1349 $urls[] = $attachment['url'];
1351 $attachments[] = ['type' => 'Page',
1352 'mediaType' => $attachment['mimetype'],
1353 'url' => $attachment['url'],
1354 'name' => $attachment['description']];
1358 return $attachments;
1362 * Callback function to replace a Friendica style mention in a mention for a summary
1364 * @param array $match Matching values for the callback
1365 * @return string Replaced mention
1366 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1368 private static function mentionAddrCallback($match)
1370 if (empty($match[1])) {
1374 $data = Contact::getByURL($match[1], false, ['addr']);
1375 if (empty($data['addr'])) {
1379 return '@' . $data['addr'];
1383 * Remove image elements since they are added as attachment
1385 * @param string $body
1387 * @return string with removed images
1389 private static function removePictures($body)
1391 // Simplify image codes
1392 $body = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '[img]$3[/img]', $body);
1393 $body = preg_replace("/\[img\=(.*?)\](.*?)\[\/img\]/ism", '[img]$1[/img]', $body);
1395 // Now remove local links
1396 $body = preg_replace_callback(
1397 '/\[url=([^\[\]]*)\]\[img\](.*)\[\/img\]\[\/url\]/Usi',
1399 // We remove the link when it is a link to a local photo page
1400 if (Photo::isLocalPage($match[1])) {
1403 // otherwise we just return the link
1404 return '[url]' . $match[1] . '[/url]';
1409 // Remove all pictures
1410 $body = preg_replace("/\[img\]([^\[\]]*)\[\/img\]/Usi", '', $body);
1416 * Fetches the "context" value for a givem item array from the "conversation" table
1418 * @param array $item
1420 * @return string with context url
1421 * @throws \Exception
1423 private static function fetchContextURLForItem($item)
1425 $conversation = DBA::selectFirst('conversation', ['conversation-href', 'conversation-uri'], ['item-uri' => $item['parent-uri']]);
1426 if (DBA::isResult($conversation) && !empty($conversation['conversation-href'])) {
1427 $context_uri = $conversation['conversation-href'];
1428 } elseif (DBA::isResult($conversation) && !empty($conversation['conversation-uri'])) {
1429 $context_uri = $conversation['conversation-uri'];
1431 $context_uri = $item['parent-uri'] . '#context';
1433 return $context_uri;
1437 * Returns if the post contains sensitive content ("nsfw")
1439 * @param integer $uri_id
1442 * @throws \Exception
1444 private static function isSensitive($uri_id)
1446 return DBA::exists('tag-view', ['uri-id' => $uri_id, 'name' => 'nsfw']);
1450 * Creates event data
1452 * @param array $item
1454 * @return array with the event data
1455 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1457 private static function createEvent($item)
1460 $event['name'] = $item['event-summary'];
1461 $event['content'] = BBCode::convertForUriId($item['uri-id'], $item['event-desc'], BBCode::ACTIVITYPUB);
1462 $event['startTime'] = DateTimeFormat::utc($item['event-start'] . '+00:00', DateTimeFormat::ATOM);
1464 if (!$item['event-nofinish']) {
1465 $event['endTime'] = DateTimeFormat::utc($item['event-finish'] . '+00:00', DateTimeFormat::ATOM);
1468 if (!empty($item['event-location'])) {
1469 $item['location'] = $item['event-location'];
1470 $event['location'] = self::createLocation($item);
1473 $event['dfrn:adjust'] = (bool)$item['event-adjust'];
1479 * Creates a note/article object array
1481 * @param array $item
1483 * @return array with the object data
1484 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1485 * @throws \ImagickException
1487 public static function createNote($item)
1493 if ($item['event-type'] == 'event') {
1495 } elseif (!empty($item['title'])) {
1501 if ($item['deleted']) {
1502 $type = 'Tombstone';
1506 $data['id'] = $item['uri'];
1507 $data['type'] = $type;
1509 if ($item['deleted']) {
1513 $data['summary'] = BBCode::toPlaintext(BBCode::getAbstract($item['body'], Protocol::ACTIVITYPUB));
1515 if ($item['uri'] != $item['thr-parent']) {
1516 $data['inReplyTo'] = $item['thr-parent'];
1518 $data['inReplyTo'] = null;
1521 $data['diaspora:guid'] = $item['guid'];
1522 $data['published'] = DateTimeFormat::utc($item['created'] . '+00:00', DateTimeFormat::ATOM);
1524 if ($item['created'] != $item['edited']) {
1525 $data['updated'] = DateTimeFormat::utc($item['edited'] . '+00:00', DateTimeFormat::ATOM);
1528 $data['url'] = $item['plink'];
1529 $data['attributedTo'] = $item['author-link'];
1530 $data['sensitive'] = self::isSensitive($item['uri-id']);
1531 $data['context'] = self::fetchContextURLForItem($item);
1533 if (!empty($item['title'])) {
1534 $data['name'] = BBCode::toPlaintext($item['title'], false);
1537 $permission_block = self::createPermissionBlockForItem($item, false);
1539 $body = $item['body'];
1541 if ($type == 'Note') {
1542 $body = $item['raw-body'] ?? self::removePictures($body);
1546 * @todo Improve the automated summary
1547 * This part is currently deactivated. The automated summary seems to be more
1548 * confusing than helping. But possibly we will find a better way.
1549 * So the code is left here for now as a reminder
1551 * } elseif (($type == 'Article') && empty($data['summary'])) {
1552 * $regexp = "/[@!]\[url\=([^\[\]]*)\].*?\[\/url\]/ism";
1553 * $summary = preg_replace_callback($regexp, ['self', 'mentionAddrCallback'], $body);
1554 * $data['summary'] = BBCode::toPlaintext(Plaintext::shorten(self::removePictures($summary), 1000));
1558 if (empty($item['uid']) || !Feature::isEnabled($item['uid'], 'explicit_mentions')) {
1559 $body = self::prependMentions($body, $item['uri-id'], $item['author-link']);
1562 if ($type == 'Event') {
1563 $data = array_merge($data, self::createEvent($item));
1565 $body = BBCode::setMentionsToNicknames($body);
1567 $data['content'] = BBCode::convertForUriId($item['uri-id'], $body, BBCode::ACTIVITYPUB);
1570 // The regular "content" field does contain a minimized HTML. This is done since systems like
1571 // Mastodon has got problems with - for example - embedded pictures.
1572 // The contentMap does contain the unmodified HTML.
1573 $language = self::getLanguage($item);
1574 if (!empty($language)) {
1575 $richbody = BBCode::setMentionsToNicknames($item['body'] ?? '');
1576 $richbody = BBCode::removeAttachment($richbody);
1578 $data['contentMap'][$language] = BBCode::convertForUriId($item['uri-id'], $richbody, BBCode::EXTERNAL);
1581 $data['source'] = ['content' => $item['body'], 'mediaType' => "text/bbcode"];
1583 if (!empty($item['signed_text']) && ($item['uri'] != $item['thr-parent'])) {
1584 $data['diaspora:comment'] = $item['signed_text'];
1587 $data['attachment'] = self::createAttachmentList($item, $type);
1588 $data['tag'] = self::createTagList($item);
1590 if (empty($data['location']) && (!empty($item['coord']) || !empty($item['location']))) {
1591 $data['location'] = self::createLocation($item);
1594 if (!empty($item['app'])) {
1595 $data['generator'] = ['type' => 'Application', 'name' => $item['app']];
1598 $data = array_merge($data, $permission_block);
1604 * Fetches the language from the post, the user or the system.
1606 * @param array $item
1608 * @return string language string
1610 private static function getLanguage(array $item)
1612 // Try to fetch the language from the post itself
1613 if (!empty($item['language'])) {
1614 $languages = array_keys(json_decode($item['language'], true));
1615 if (!empty($languages[0])) {
1616 return $languages[0];
1620 // Otherwise use the user's language
1621 if (!empty($item['uid'])) {
1622 $user = DBA::selectFirst('user', ['language'], ['uid' => $item['uid']]);
1623 if (!empty($user['language'])) {
1624 return $user['language'];
1628 // And finally just use the system language
1629 return DI::config()->get('system', 'language');
1633 * Creates an an "add tag" entry
1635 * @param array $item
1636 * @param array $data activity data
1638 * @return array with activity data for adding tags
1639 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1640 * @throws \ImagickException
1642 private static function createAddTag($item, $data)
1644 $object = XML::parseString($item['object']);
1645 $target = XML::parseString($item["target"]);
1647 $data['diaspora:guid'] = $item['guid'];
1648 $data['actor'] = $item['author-link'];
1649 $data['target'] = (string)$target->id;
1650 $data['summary'] = BBCode::toPlaintext($item['body']);
1651 $data['object'] = ['id' => (string)$object->id, 'type' => 'tag', 'name' => (string)$object->title, 'content' => (string)$object->content];
1657 * Creates an announce object entry
1659 * @param array $item
1660 * @param array $data activity data
1662 * @return array with activity data
1663 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1664 * @throws \ImagickException
1666 private static function createAnnounce($item, $data)
1668 $orig_body = $item['body'];
1669 $announce = self::getAnnounceArray($item);
1670 if (empty($announce)) {
1671 $data['type'] = 'Create';
1672 $data['object'] = self::createNote($item);
1676 if (empty($announce['comment'])) {
1677 // Pure announce, without a quote
1678 $data['type'] = 'Announce';
1679 $data['object'] = $announce['object']['uri'];
1684 $data['type'] = 'Create';
1685 $item['body'] = $announce['comment'] . "\n" . $announce['object']['plink'];
1686 $data['object'] = self::createNote($item);
1688 /// @todo Finally descide how to implement this in AP. This is a possible way:
1689 $data['object']['attachment'][] = self::createNote($announce['object']);
1691 $data['object']['source']['content'] = $orig_body;
1696 * Return announce related data if the item is an annunce
1698 * @param array $item
1702 public static function getAnnounceArray($item)
1704 $reshared = Item::getShareArray($item);
1705 if (empty($reshared['guid'])) {
1709 $reshared_item = Post::selectFirst(Item::DELIVER_FIELDLIST, ['guid' => $reshared['guid']]);
1710 if (!DBA::isResult($reshared_item)) {
1714 if (!in_array($reshared_item['network'], [Protocol::ACTIVITYPUB, Protocol::DFRN])) {
1718 $profile = APContact::getByURL($reshared_item['author-link'], false);
1719 if (empty($profile)) {
1723 return ['object' => $reshared_item, 'actor' => $profile, 'comment' => $reshared['comment']];
1727 * Checks if the provided item array is an announce
1729 * @param array $item
1733 public static function isAnnounce($item)
1735 if (!empty($item['verb']) && ($item['verb'] == Activity::ANNOUNCE)) {
1739 $announce = self::getAnnounceArray($item);
1740 if (empty($announce)) {
1744 return empty($announce['comment']);
1748 * Creates an activity id for a given contact id
1750 * @param integer $cid Contact ID of target
1752 * @return bool|string activity id
1754 public static function activityIDFromContact($cid)
1756 $contact = DBA::selectFirst('contact', ['uid', 'id', 'created'], ['id' => $cid]);
1757 if (!DBA::isResult($contact)) {
1761 $hash = hash('ripemd128', $contact['uid'].'-'.$contact['id'].'-'.$contact['created']);
1762 $uuid = substr($hash, 0, 8). '-' . substr($hash, 8, 4) . '-' . substr($hash, 12, 4) . '-' . substr($hash, 16, 4) . '-' . substr($hash, 20, 12);
1763 return DI::baseUrl() . '/activity/' . $uuid;
1767 * Transmits a contact suggestion to a given inbox
1769 * @param integer $uid User ID
1770 * @param string $inbox Target inbox
1771 * @param integer $suggestion_id Suggestion ID
1773 * @return boolean was the transmission successful?
1774 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1776 public static function sendContactSuggestion($uid, $inbox, $suggestion_id)
1778 $owner = User::getOwnerDataById($uid);
1780 $suggestion = DI::fsuggest()->getById($suggestion_id);
1782 $data = ['@context' => ActivityPub::CONTEXT,
1783 'id' => DI::baseUrl() . '/activity/' . System::createGUID(),
1784 'type' => 'Announce',
1785 'actor' => $owner['url'],
1786 'object' => $suggestion->url,
1787 'content' => $suggestion->note,
1788 'instrument' => self::getService(),
1789 'to' => [ActivityPub::PUBLIC_COLLECTION],
1792 $signed = LDSignature::sign($data, $owner);
1794 Logger::log('Deliver profile deletion for user ' . $uid . ' to ' . $inbox . ' via ActivityPub', Logger::DEBUG);
1795 return HTTPSignature::transmit($signed, $inbox, $uid);
1799 * Transmits a profile relocation to a given inbox
1801 * @param integer $uid User ID
1802 * @param string $inbox Target inbox
1804 * @return boolean was the transmission successful?
1805 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1807 public static function sendProfileRelocation($uid, $inbox)
1809 $owner = User::getOwnerDataById($uid);
1811 $data = ['@context' => ActivityPub::CONTEXT,
1812 'id' => DI::baseUrl() . '/activity/' . System::createGUID(),
1813 'type' => 'dfrn:relocate',
1814 'actor' => $owner['url'],
1815 'object' => $owner['url'],
1816 'published' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
1817 'instrument' => self::getService(),
1818 'to' => [ActivityPub::PUBLIC_COLLECTION],
1821 $signed = LDSignature::sign($data, $owner);
1823 Logger::log('Deliver profile relocation for user ' . $uid . ' to ' . $inbox . ' via ActivityPub', Logger::DEBUG);
1824 return HTTPSignature::transmit($signed, $inbox, $uid);
1828 * Transmits a profile deletion to a given inbox
1830 * @param integer $uid User ID
1831 * @param string $inbox Target inbox
1833 * @return boolean was the transmission successful?
1834 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1836 public static function sendProfileDeletion($uid, $inbox)
1838 $owner = User::getOwnerDataById($uid);
1840 if (empty($owner)) {
1841 Logger::error('No owner data found, the deletion message cannot be processed.', ['user' => $uid]);
1845 if (empty($owner['uprvkey'])) {
1846 Logger::error('No private key for owner found, the deletion message cannot be processed.', ['user' => $uid]);
1850 $data = ['@context' => ActivityPub::CONTEXT,
1851 'id' => DI::baseUrl() . '/activity/' . System::createGUID(),
1853 'actor' => $owner['url'],
1854 'object' => $owner['url'],
1855 'published' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
1856 'instrument' => self::getService(),
1857 'to' => [ActivityPub::PUBLIC_COLLECTION],
1860 $signed = LDSignature::sign($data, $owner);
1862 Logger::log('Deliver profile deletion for user ' . $uid . ' to ' . $inbox . ' via ActivityPub', Logger::DEBUG);
1863 return HTTPSignature::transmit($signed, $inbox, $uid);
1867 * Transmits a profile change to a given inbox
1869 * @param integer $uid User ID
1870 * @param string $inbox Target inbox
1872 * @return boolean was the transmission successful?
1873 * @throws HTTPException\InternalServerErrorException
1874 * @throws HTTPException\NotFoundException
1875 * @throws \ImagickException
1877 public static function sendProfileUpdate(int $uid, string $inbox): bool
1879 $owner = User::getOwnerDataById($uid);
1880 $profile = APContact::getByURL($owner['url']);
1882 $data = ['@context' => ActivityPub::CONTEXT,
1883 'id' => DI::baseUrl() . '/activity/' . System::createGUID(),
1885 'actor' => $owner['url'],
1886 'object' => self::getProfile($uid),
1887 'published' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
1888 'instrument' => self::getService(),
1889 'to' => [$profile['followers']],
1892 $signed = LDSignature::sign($data, $owner);
1894 Logger::log('Deliver profile update for user ' . $uid . ' to ' . $inbox . ' via ActivityPub', Logger::DEBUG);
1895 return HTTPSignature::transmit($signed, $inbox, $uid);
1899 * Transmits a given activity to a target
1901 * @param string $activity Type name
1902 * @param string $target Target profile
1903 * @param integer $uid User ID
1905 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1906 * @throws \ImagickException
1907 * @throws \Exception
1909 public static function sendActivity($activity, $target, $uid, $id = '')
1911 $profile = APContact::getByURL($target);
1912 if (empty($profile['inbox'])) {
1913 Logger::warning('No inbox found for target', ['target' => $target, 'profile' => $profile]);
1917 $owner = User::getOwnerDataById($uid);
1920 $id = DI::baseUrl() . '/activity/' . System::createGUID();
1923 $data = ['@context' => ActivityPub::CONTEXT,
1925 'type' => $activity,
1926 'actor' => $owner['url'],
1927 'object' => $profile['url'],
1928 'instrument' => self::getService(),
1929 'to' => [$profile['url']]];
1931 Logger::log('Sending activity ' . $activity . ' to ' . $target . ' for user ' . $uid, Logger::DEBUG);
1933 $signed = LDSignature::sign($data, $owner);
1934 return HTTPSignature::transmit($signed, $profile['inbox'], $uid);
1938 * Transmits a "follow object" activity to a target
1939 * This is a preparation for sending automated "follow" requests when receiving "Announce" messages
1941 * @param string $object Object URL
1942 * @param string $target Target profile
1943 * @param integer $uid User ID
1945 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1946 * @throws \ImagickException
1947 * @throws \Exception
1949 public static function sendFollowObject($object, $target, $uid = 0)
1951 $profile = APContact::getByURL($target);
1952 if (empty($profile['inbox'])) {
1953 Logger::warning('No inbox found for target', ['target' => $target, 'profile' => $profile]);
1958 // Fetch the list of administrators
1959 $admin_mail = explode(',', str_replace(' ', '', DI::config()->get('config', 'admin_email')));
1961 // We need to use some user as a sender. It doesn't care who it will send. We will use an administrator account.
1962 $condition = ['verified' => true, 'blocked' => false, 'account_removed' => false, 'account_expired' => false, 'email' => $admin_mail];
1963 $first_user = DBA::selectFirst('user', ['uid'], $condition);
1964 $uid = $first_user['uid'];
1967 $condition = ['verb' => Activity::FOLLOW, 'uid' => 0, 'parent-uri' => $object,
1968 'author-id' => Contact::getPublicIdByUserId($uid)];
1969 if (Post::exists($condition)) {
1970 Logger::log('Follow for ' . $object . ' for user ' . $uid . ' does already exist.', Logger::DEBUG);
1974 $owner = User::getOwnerDataById($uid);
1976 $data = ['@context' => ActivityPub::CONTEXT,
1977 'id' => DI::baseUrl() . '/activity/' . System::createGUID(),
1979 'actor' => $owner['url'],
1980 'object' => $object,
1981 'instrument' => self::getService(),
1982 'to' => [$profile['url']]];
1984 Logger::log('Sending follow ' . $object . ' to ' . $target . ' for user ' . $uid, Logger::DEBUG);
1986 $signed = LDSignature::sign($data, $owner);
1987 return HTTPSignature::transmit($signed, $profile['inbox'], $uid);
1991 * Transmit a message that the contact request had been accepted
1993 * @param string $target Target profile
1995 * @param integer $uid User ID
1996 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1997 * @throws \ImagickException
1999 public static function sendContactAccept($target, $id, $uid)
2001 $profile = APContact::getByURL($target);
2002 if (empty($profile['inbox'])) {
2003 Logger::warning('No inbox found for target', ['target' => $target, 'profile' => $profile]);
2007 $owner = User::getOwnerDataById($uid);
2008 $data = ['@context' => ActivityPub::CONTEXT,
2009 'id' => DI::baseUrl() . '/activity/' . System::createGUID(),
2011 'actor' => $owner['url'],
2013 'id' => (string)$id,
2015 'actor' => $profile['url'],
2016 'object' => $owner['url']
2018 'instrument' => self::getService(),
2019 'to' => [$profile['url']]];
2021 Logger::debug('Sending accept to ' . $target . ' for user ' . $uid . ' with id ' . $id);
2023 $signed = LDSignature::sign($data, $owner);
2024 HTTPSignature::transmit($signed, $profile['inbox'], $uid);
2028 * Reject a contact request or terminates the contact relation
2030 * @param string $target Target profile
2032 * @param integer $uid User ID
2033 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2034 * @throws \ImagickException
2036 public static function sendContactReject($target, $id, $uid)
2038 $profile = APContact::getByURL($target);
2039 if (empty($profile['inbox'])) {
2040 Logger::warning('No inbox found for target', ['target' => $target, 'profile' => $profile]);
2044 $owner = User::getOwnerDataById($uid);
2045 $data = ['@context' => ActivityPub::CONTEXT,
2046 'id' => DI::baseUrl() . '/activity/' . System::createGUID(),
2048 'actor' => $owner['url'],
2050 'id' => (string)$id,
2052 'actor' => $profile['url'],
2053 'object' => $owner['url']
2055 'instrument' => self::getService(),
2056 'to' => [$profile['url']]];
2058 Logger::debug('Sending reject to ' . $target . ' for user ' . $uid . ' with id ' . $id);
2060 $signed = LDSignature::sign($data, $owner);
2061 HTTPSignature::transmit($signed, $profile['inbox'], $uid);
2065 * Transmits a message that we don't want to follow this contact anymore
2067 * @param string $target Target profile
2068 * @param integer $uid User ID
2069 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2070 * @throws \ImagickException
2071 * @throws \Exception
2072 * @return bool success
2074 public static function sendContactUndo($target, $cid, $uid)
2076 $profile = APContact::getByURL($target);
2077 if (empty($profile['inbox'])) {
2078 Logger::warning('No inbox found for target', ['target' => $target, 'profile' => $profile]);
2082 $object_id = self::activityIDFromContact($cid);
2083 if (empty($object_id)) {
2087 $id = DI::baseUrl() . '/activity/' . System::createGUID();
2089 $owner = User::getOwnerDataById($uid);
2090 $data = ['@context' => ActivityPub::CONTEXT,
2093 'actor' => $owner['url'],
2094 'object' => ['id' => $object_id, 'type' => 'Follow',
2095 'actor' => $owner['url'],
2096 'object' => $profile['url']],
2097 'instrument' => self::getService(),
2098 'to' => [$profile['url']]];
2100 Logger::log('Sending undo to ' . $target . ' for user ' . $uid . ' with id ' . $id, Logger::DEBUG);
2102 $signed = LDSignature::sign($data, $owner);
2103 return HTTPSignature::transmit($signed, $profile['inbox'], $uid);
2106 private static function prependMentions($body, int $uriid, string $authorLink)
2110 foreach (Tag::getByURIId($uriid, [Tag::IMPLICIT_MENTION]) as $tag) {
2111 $profile = Contact::getByURL($tag['url'], false, ['addr', 'contact-type', 'nick']);
2112 if (!empty($profile['addr'])
2113 && $profile['contact-type'] != Contact::TYPE_COMMUNITY
2114 && !strstr($body, $profile['addr'])
2115 && !strstr($body, $tag['url'])
2116 && $tag['url'] !== $authorLink
2118 $mentions[] = '@[url=' . $tag['url'] . ']' . $profile['nick'] . '[/url]';
2122 $mentions[] = $body;
2124 return implode(' ', $mentions);