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 Contact::update(['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 Contact::update(['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' => User::getAvatarUrl($owner)];
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'];
397 foreach (DI::profileField()->selectByContactId(0, $uid) as $profile_field) {
399 'type' => 'PropertyValue',
400 'name' => $profile_field->label,
401 'value' => BBCode::convertForUriId($owner['uri-id'], $profile_field->value)
405 if (!empty($custom_fields)) {
406 $data['attachment'] = $custom_fields;
409 $data['generator'] = self::getService();
411 // tags: https://kitty.town/@inmysocks/100656097926961126.json
416 * @param string $username
418 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
420 public static function getDeletedUser($username)
423 '@context' => ActivityPub::CONTEXT,
424 'id' => DI::baseUrl() . '/profile/' . $username,
425 'type' => 'Tombstone',
426 'published' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
427 'updated' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
428 'deleted' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
433 * Returns an array with permissions of a given item array
437 * @return array with permissions
438 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
439 * @throws \ImagickException
441 private static function fetchPermissionBlockFromConversation($item)
443 if (empty($item['thr-parent'])) {
447 $condition = ['item-uri' => $item['thr-parent'], 'protocol' => Conversation::PARCEL_ACTIVITYPUB];
448 $conversation = DBA::selectFirst('conversation', ['source'], $condition);
449 if (!DBA::isResult($conversation)) {
453 $activity = json_decode($conversation['source'], true);
455 $actor = JsonLD::fetchElement($activity, 'actor', 'id');
456 if (!empty($actor)) {
457 $permissions['to'][] = $actor;
458 $profile = APContact::getByURL($actor);
463 $item_profile = APContact::getByURL($item['author-link']);
464 $exclude[] = $item['author-link'];
466 if ($item['gravity'] == GRAVITY_PARENT) {
467 $exclude[] = $item['owner-link'];
470 foreach (['to', 'cc', 'bto', 'bcc'] as $element) {
471 if (empty($activity[$element])) {
474 if (is_string($activity[$element])) {
475 $activity[$element] = [$activity[$element]];
478 foreach ($activity[$element] as $receiver) {
479 if (empty($receiver)) {
483 if (!empty($profile['followers']) && $receiver == $profile['followers'] && !empty($item_profile['followers'])) {
484 $permissions[$element][] = $item_profile['followers'];
485 } elseif (!in_array($receiver, $exclude)) {
486 $permissions[$element][] = $receiver;
494 * Check if the given item id is from ActivityPub
496 * @param integer $item_id
497 * @return boolean "true" if the post is from ActivityPub
499 private static function isAPPost(int $item_id)
501 if (empty($item_id)) {
505 return Post::exists(['id' => $item_id, 'network' => Protocol::ACTIVITYPUB]);
509 * Creates an array of permissions from an item thread
511 * @param array $item Item array
512 * @param boolean $blindcopy addressing via "bcc" or "cc"?
513 * @param integer $last_id Last item id for adding receivers
514 * @param boolean $forum_mode "true" means that we are sending content to a forum
516 * @return array with permission data
517 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
518 * @throws \ImagickException
520 private static function createPermissionBlockForItem($item, $blindcopy, $last_id = 0, $forum_mode = false)
523 $last_id = $item['id'];
528 // Check if we should always deliver our stuff via BCC
529 if (!empty($item['uid'])) {
530 $profile = User::getOwnerDataById($item['uid']);
531 if (!empty($profile)) {
532 $always_bcc = $profile['hide-friends'];
536 if (DI::config()->get('system', 'ap_always_bcc')) {
540 if (self::isAnnounce($item) || DI::config()->get('debug', 'total_ap_delivery') || self::isAPPost($last_id)) {
541 // Will be activated in a later step
542 $networks = Protocol::FEDERATED;
544 // For now only send to these contacts:
545 $networks = [Protocol::ACTIVITYPUB, Protocol::OSTATUS];
548 $data = ['to' => [], 'cc' => [], 'bcc' => []];
550 if ($item['gravity'] == GRAVITY_PARENT) {
551 $actor_profile = APContact::getByURL($item['owner-link']);
553 $actor_profile = APContact::getByURL($item['author-link']);
558 $terms = Tag::getByURIId($item['uri-id'], [Tag::MENTION, Tag::IMPLICIT_MENTION, Tag::EXCLUSIVE_MENTION]);
560 if ($item['private'] != Item::PRIVATE) {
561 // Directly mention the original author upon a quoted reshare.
562 // Else just ensure that the original author receives the reshare.
563 $announce = self::getAnnounceArray($item);
564 if (!empty($announce['comment'])) {
565 $data['to'][] = $announce['actor']['url'];
566 } elseif (!empty($announce)) {
567 $data['cc'][] = $announce['actor']['url'];
570 $data = array_merge($data, self::fetchPermissionBlockFromConversation($item));
572 // Check if the item is completely public or unlisted
573 if ($item['private'] == Item::PUBLIC) {
574 $data['to'][] = ActivityPub::PUBLIC_COLLECTION;
576 $data['cc'][] = ActivityPub::PUBLIC_COLLECTION;
579 foreach ($terms as $term) {
580 $profile = APContact::getByURL($term['url'], false);
581 if (!empty($profile)) {
582 if ($term['type'] == Tag::EXCLUSIVE_MENTION) {
584 if (!empty($profile['followers']) && ($profile['type'] == 'Group')) {
585 $data['cc'][] = $profile['followers'];
588 $data['to'][] = $profile['url'];
592 $receiver_list = Item::enumeratePermissions($item, true);
594 foreach ($terms as $term) {
595 $cid = Contact::getIdForURL($term['url'], $item['uid']);
596 if (!empty($cid) && in_array($cid, $receiver_list)) {
597 $contact = DBA::selectFirst('contact', ['url', 'network', 'protocol', 'gsid'], ['id' => $cid, 'network' => Protocol::FEDERATED]);
598 if (!DBA::isResult($contact) || !self::isAPContact($contact, $networks)) {
602 if (!empty($profile = APContact::getByURL($contact['url'], false))) {
603 $data['to'][] = $profile['url'];
608 foreach ($receiver_list as $receiver) {
609 $contact = DBA::selectFirst('contact', ['url', 'hidden', 'network', 'protocol', 'gsid'], ['id' => $receiver, 'network' => Protocol::FEDERATED]);
610 if (!DBA::isResult($contact) || !self::isAPContact($contact, $networks)) {
614 if (!empty($profile = APContact::getByURL($contact['url'], false))) {
615 if ($contact['hidden'] || $always_bcc) {
616 $data['bcc'][] = $profile['url'];
618 $data['cc'][] = $profile['url'];
624 if (!empty($item['parent'])) {
625 $parents = Post::select(['id', 'author-link', 'owner-link', 'gravity', 'uri'], ['parent' => $item['parent']]);
626 while ($parent = Post::fetch($parents)) {
627 if ($parent['gravity'] == GRAVITY_PARENT) {
628 $profile = APContact::getByURL($parent['owner-link'], false);
629 if (!empty($profile)) {
630 if ($item['gravity'] != GRAVITY_PARENT) {
631 // Comments to forums are directed to the forum
632 // But comments to forums aren't directed to the followers collection
633 // This rule is only valid when the actor isn't the forum.
634 // The forum needs to transmit their content to their followers.
635 if (($profile['type'] == 'Group') && ($profile['url'] != ($actor_profile['url'] ?? ''))) {
636 $data['to'][] = $profile['url'];
638 $data['cc'][] = $profile['url'];
639 if (($item['private'] != Item::PRIVATE) && !empty($actor_profile['followers'])) {
640 $data['cc'][] = $actor_profile['followers'];
643 } elseif (!$exclusive) {
644 // Public thread parent post always are directed to the followers.
645 // This mustn't be done by posts that are directed to forum servers via the exclusive mention.
646 // But possibly in that case we could add the "followers" collection of the forum to the message.
647 if (($item['private'] != Item::PRIVATE) && !$forum_mode) {
648 $data['cc'][] = $actor_profile['followers'];
654 // Don't include data from future posts
655 if ($parent['id'] >= $last_id) {
659 $profile = APContact::getByURL($parent['author-link'], false);
660 if (!empty($profile)) {
661 if (($profile['type'] == 'Group') || ($parent['uri'] == $item['thr-parent'])) {
662 $data['to'][] = $profile['url'];
664 $data['cc'][] = $profile['url'];
668 DBA::close($parents);
671 $data['to'] = array_unique($data['to']);
672 $data['cc'] = array_unique($data['cc']);
673 $data['bcc'] = array_unique($data['bcc']);
675 if (($key = array_search($item['author-link'], $data['to'])) !== false) {
676 unset($data['to'][$key]);
679 if (($key = array_search($item['author-link'], $data['cc'])) !== false) {
680 unset($data['cc'][$key]);
683 if (($key = array_search($item['author-link'], $data['bcc'])) !== false) {
684 unset($data['bcc'][$key]);
687 foreach ($data['to'] as $to) {
688 if (($key = array_search($to, $data['cc'])) !== false) {
689 unset($data['cc'][$key]);
692 if (($key = array_search($to, $data['bcc'])) !== false) {
693 unset($data['bcc'][$key]);
697 foreach ($data['cc'] as $cc) {
698 if (($key = array_search($cc, $data['bcc'])) !== false) {
699 unset($data['bcc'][$key]);
703 $receivers = ['to' => array_values($data['to']), 'cc' => array_values($data['cc']), 'bcc' => array_values($data['bcc'])];
706 unset($receivers['bcc']);
713 * Check if an inbox is archived
715 * @param string $url Inbox url
717 * @return boolean "true" if inbox is archived
719 public static function archivedInbox($url)
721 return DBA::exists('inbox-status', ['url' => $url, 'archive' => true]);
725 * Check if a given contact should be delivered via AP
727 * @param array $contact
728 * @param array $networks
732 private static function isAPContact(array $contact, array $networks)
734 if (in_array($contact['network'], $networks) || ($contact['protocol'] == Protocol::ACTIVITYPUB)) {
738 return GServer::getProtocol($contact['gsid'] ?? 0) == Post\DeliveryData::ACTIVITYPUB;
742 * Fetches a list of inboxes of followers of a given user
744 * @param integer $uid User ID
745 * @param boolean $personal fetch personal inboxes
746 * @param boolean $all_ap Retrieve all AP enabled inboxes
748 * @return array of follower inboxes
749 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
750 * @throws \ImagickException
752 public static function fetchTargetInboxesforUser($uid, $personal = false, bool $all_ap = false)
758 if (!empty($item['uid'])) {
759 $profile = User::getOwnerDataById($item['uid']);
760 if (!empty($profile)) {
761 $isforum = $profile['account-type'] == User::ACCOUNT_TYPE_COMMUNITY;
765 if (DI::config()->get('debug', 'total_ap_delivery') || $all_ap) {
766 // Will be activated in a later step
767 $networks = Protocol::FEDERATED;
769 // For now only send to these contacts:
770 $networks = [Protocol::ACTIVITYPUB, Protocol::OSTATUS];
773 $condition = ['uid' => $uid, 'archive' => false, 'pending' => false, 'blocked' => false, 'network' => Protocol::FEDERATED];
776 $condition['rel'] = [Contact::FOLLOWER, Contact::FRIEND];
779 $contacts = DBA::select('contact', ['id', 'url', 'network', 'protocol', 'gsid'], $condition);
780 while ($contact = DBA::fetch($contacts)) {
781 if (!self::isAPContact($contact, $networks)) {
785 if ($isforum && ($contact['network'] == Protocol::DFRN)) {
789 if (Network::isUrlBlocked($contact['url'])) {
793 $profile = APContact::getByURL($contact['url'], false);
794 if (!empty($profile)) {
795 if (empty($profile['sharedinbox']) || $personal || Contact::isLocal($contact['url'])) {
796 $target = $profile['inbox'];
798 $target = $profile['sharedinbox'];
800 if (!self::archivedInbox($target)) {
801 $inboxes[$target][] = $contact['id'];
805 DBA::close($contacts);
811 * Fetches an array of inboxes for the given item and user
813 * @param array $item Item array
814 * @param integer $uid User ID
815 * @param boolean $personal fetch personal inboxes
816 * @param integer $last_id Last item id for adding receivers
817 * @param boolean $forum_mode "true" means that we are sending content to a forum
818 * @return array with inboxes
819 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
820 * @throws \ImagickException
822 public static function fetchTargetInboxes($item, $uid, $personal = false, $last_id = 0, $forum_mode = false)
824 $permissions = self::createPermissionBlockForItem($item, true, $last_id, $forum_mode);
825 if (empty($permissions)) {
831 if ($item['gravity'] == GRAVITY_ACTIVITY) {
832 $item_profile = APContact::getByURL($item['author-link'], false);
834 $item_profile = APContact::getByURL($item['owner-link'], false);
837 if (empty($item_profile)) {
841 $profile_uid = User::getIdForURL($item_profile['url']);
843 foreach (['to', 'cc', 'bto', 'bcc'] as $element) {
844 if (empty($permissions[$element])) {
848 $blindcopy = in_array($element, ['bto', 'bcc']);
850 foreach ($permissions[$element] as $receiver) {
851 if (empty($receiver) || Network::isUrlBlocked($receiver)) {
855 if ($item_profile && ($receiver == $item_profile['followers']) && ($uid == $profile_uid)) {
856 $inboxes = array_merge($inboxes, self::fetchTargetInboxesforUser($uid, $personal, self::isAPPost($last_id)));
858 $profile = APContact::getByURL($receiver, false);
859 if (!empty($profile)) {
860 $contact = Contact::getByURLForUser($receiver, $uid, false, ['id']);
862 if (empty($profile['sharedinbox']) || $personal || $blindcopy || Contact::isLocal($receiver)) {
863 $target = $profile['inbox'];
865 $target = $profile['sharedinbox'];
867 if (!self::archivedInbox($target)) {
868 $inboxes[$target][] = $contact['id'] ?? 0;
879 * Creates an array in the structure of the item table for a given mail id
881 * @param integer $mail_id
886 public static function ItemArrayFromMail($mail_id, $use_title = false)
888 $mail = DBA::selectFirst('mail', [], ['id' => $mail_id]);
889 if (!DBA::isResult($mail)) {
893 $reply = DBA::selectFirst('mail', ['uri', 'uri-id', 'from-url'], ['parent-uri' => $mail['parent-uri'], 'reply' => false]);
894 if (!DBA::isResult($reply)) {
898 // Making the post more compatible for Mastodon by:
899 // - Making it a note and not an article (no title)
900 // - Moving the title into the "summary" field that is used as a "content warning"
903 $mail['body'] = '[abstract]' . $mail['title'] . "[/abstract]\n" . $mail['body'];
907 $mail['author-link'] = $mail['owner-link'] = $mail['from-url'];
908 $mail['owner-id'] = $mail['author-id'];
909 $mail['allow_cid'] = '<'.$mail['contact-id'].'>';
910 $mail['allow_gid'] = '';
911 $mail['deny_cid'] = '';
912 $mail['deny_gid'] = '';
913 $mail['private'] = Item::PRIVATE;
914 $mail['deleted'] = false;
915 $mail['edited'] = $mail['created'];
916 $mail['plink'] = DI::baseUrl() . '/message/' . $mail['id'];
917 $mail['parent-uri'] = $reply['uri'];
918 $mail['parent-uri-id'] = $reply['uri-id'];
919 $mail['parent-author-id'] = Contact::getIdForURL($reply['from-url'], 0, false);
920 $mail['gravity'] = ($mail['reply'] ? GRAVITY_COMMENT: GRAVITY_PARENT);
921 $mail['event-type'] = '';
922 $mail['language'] = '';
929 * Creates an activity array for a given mail id
931 * @param integer $mail_id
932 * @param boolean $object_mode Is the activity item is used inside another object?
934 * @return array of activity
937 public static function createActivityFromMail($mail_id, $object_mode = false)
939 $mail = self::ItemArrayFromMail($mail_id);
943 $object = self::createNote($mail);
946 $data = ['@context' => ActivityPub::CONTEXT];
951 $data['id'] = $mail['uri'] . '/Create';
952 $data['type'] = 'Create';
953 $data['actor'] = $mail['author-link'];
954 $data['published'] = DateTimeFormat::utc($mail['created'] . '+00:00', DateTimeFormat::ATOM);
955 $data['instrument'] = self::getService();
956 $data = array_merge($data, self::createPermissionBlockForItem($mail, true));
958 if (empty($data['to']) && !empty($data['cc'])) {
959 $data['to'] = $data['cc'];
962 if (empty($data['to']) && !empty($data['bcc'])) {
963 $data['to'] = $data['bcc'];
969 $object['to'] = $data['to'];
970 $object['tag'] = [['type' => 'Mention', 'href' => $object['to'][0], 'name' => '']];
972 unset($object['cc']);
973 unset($object['bcc']);
975 $data['directMessage'] = true;
977 $data['object'] = $object;
979 $owner = User::getOwnerDataById($mail['uid']);
981 if (!$object_mode && !empty($owner)) {
982 return LDSignature::sign($data, $owner);
989 * Returns the activity type of a given item
993 * @return string with activity type
994 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
995 * @throws \ImagickException
997 private static function getTypeOfItem($item)
1001 // Only check for a reshare, if it is a real reshare and no quoted reshare
1002 if (strpos($item['body'], "[share") === 0) {
1003 $announce = self::getAnnounceArray($item);
1004 $reshared = !empty($announce);
1009 } elseif ($item['verb'] == Activity::POST) {
1010 if ($item['created'] == $item['edited']) {
1015 } elseif ($item['verb'] == Activity::LIKE) {
1017 } elseif ($item['verb'] == Activity::DISLIKE) {
1019 } elseif ($item['verb'] == Activity::ATTEND) {
1021 } elseif ($item['verb'] == Activity::ATTENDNO) {
1023 } elseif ($item['verb'] == Activity::ATTENDMAYBE) {
1024 $type = 'TentativeAccept';
1025 } elseif ($item['verb'] == Activity::FOLLOW) {
1027 } elseif ($item['verb'] == Activity::TAG) {
1029 } elseif ($item['verb'] == Activity::ANNOUNCE) {
1039 * Creates the activity or fetches it from the cache
1041 * @param integer $item_id
1042 * @param boolean $force Force new cache entry
1044 * @return array with the activity
1045 * @throws \Exception
1047 public static function createCachedActivityFromItem($item_id, $force = false)
1049 $cachekey = 'APDelivery:createActivity:' . $item_id;
1052 $data = DI::cache()->get($cachekey);
1053 if (!is_null($data)) {
1058 $data = self::createActivityFromItem($item_id);
1060 DI::cache()->set($cachekey, $data, Duration::QUARTER_HOUR);
1065 * Creates an activity array for a given item id
1067 * @param integer $item_id
1068 * @param boolean $object_mode Is the activity item is used inside another object?
1070 * @return false|array
1071 * @throws \Exception
1073 public static function createActivityFromItem(int $item_id, bool $object_mode = false)
1075 Logger::info('Fetching activity', ['item' => $item_id]);
1076 $item = Post::selectFirst(Item::DELIVER_FIELDLIST, ['id' => $item_id, 'parent-network' => Protocol::NATIVE_SUPPORT]);
1077 if (!DBA::isResult($item)) {
1081 // In case of a forum post ensure to return the original post if author and forum are on the same machine
1082 if (($item['gravity'] == GRAVITY_PARENT) && !empty($item['forum_mode'])) {
1083 $author = Contact::getById($item['author-id'], ['nurl']);
1084 if (!empty($author['nurl'])) {
1085 $self = Contact::selectFirst(['uid'], ['nurl' => $author['nurl'], 'self' => true]);
1086 if (!empty($self['uid'])) {
1087 $forum_item = Post::selectFirst(Item::DELIVER_FIELDLIST, ['uri-id' => $item['uri-id'], 'uid' => $self['uid']]);
1088 if (DBA::isResult($forum_item)) {
1089 $item = $forum_item;
1095 if (empty($item['uri-id'])) {
1096 Logger::warning('Item without uri-id', ['item' => $item]);
1100 if (!$item['deleted']) {
1101 $condition = ['item-uri' => $item['uri'], 'protocol' => Conversation::PARCEL_ACTIVITYPUB];
1102 $conversation = DBA::selectFirst('conversation', ['source'], $condition);
1103 if (!$item['origin'] && DBA::isResult($conversation)) {
1104 $data = json_decode($conversation['source'], true);
1105 if (!empty($data['type'])) {
1106 if (in_array($data['type'], ['Create', 'Update'])) {
1108 unset($data['@context']);
1109 unset($data['signature']);
1111 Logger::info('Return stored conversation', ['item' => $item_id]);
1113 } elseif (in_array('as:' . $data['type'], Receiver::CONTENT_TYPES)) {
1114 if (!empty($data['@context'])) {
1115 $context = $data['@context'];
1116 unset($data['@context']);
1118 unset($data['actor']);
1125 $type = self::getTypeOfItem($item);
1127 if (!$object_mode) {
1128 $data = ['@context' => $context ?? ActivityPub::CONTEXT];
1130 if ($item['deleted'] && ($item['gravity'] == GRAVITY_ACTIVITY)) {
1132 } elseif ($item['deleted']) {
1139 if ($type == 'Delete') {
1140 $data['id'] = Item::newURI($item['uid'], $item['guid']) . '/' . $type;;
1141 } elseif (($item['gravity'] == GRAVITY_ACTIVITY) && ($type != 'Undo')) {
1142 $data['id'] = $item['uri'];
1144 $data['id'] = $item['uri'] . '/' . $type;
1147 $data['type'] = $type;
1149 if (($type != 'Announce') || ($item['gravity'] != GRAVITY_PARENT)) {
1150 $data['actor'] = $item['author-link'];
1152 $data['actor'] = $item['owner-link'];
1155 $data['published'] = DateTimeFormat::utc($item['created'] . '+00:00', DateTimeFormat::ATOM);
1157 $data['instrument'] = self::getService();
1159 $data = array_merge($data, self::createPermissionBlockForItem($item, false));
1161 if (in_array($data['type'], ['Create', 'Update', 'Delete'])) {
1162 $data['object'] = $object ?? self::createNote($item);
1163 } elseif ($data['type'] == 'Add') {
1164 $data = self::createAddTag($item, $data);
1165 } elseif ($data['type'] == 'Announce') {
1166 if ($item['verb'] == ACTIVITY::ANNOUNCE) {
1167 $data['object'] = $item['thr-parent'];
1169 $data = self::createAnnounce($item, $data);
1171 } elseif ($data['type'] == 'Follow') {
1172 $data['object'] = $item['parent-uri'];
1173 } elseif ($data['type'] == 'Undo') {
1174 $data['object'] = self::createActivityFromItem($item_id, true);
1176 $data['diaspora:guid'] = $item['guid'];
1177 if (!empty($item['signed_text'])) {
1178 $data['diaspora:like'] = $item['signed_text'];
1180 $data['object'] = $item['thr-parent'];
1183 if (!empty($item['contact-uid'])) {
1184 $uid = $item['contact-uid'];
1186 $uid = $item['uid'];
1189 $owner = User::getOwnerDataById($uid);
1191 Logger::info('Fetched activity', ['item' => $item_id, 'uid' => $uid]);
1193 // We don't sign if we aren't the actor. This is important for relaying content especially for forums
1194 if (!$object_mode && !empty($owner) && ($data['actor'] == $owner['url'])) {
1195 return LDSignature::sign($data, $owner);
1200 /// @todo Create "conversation" entry
1204 * Creates a location entry for a given item array
1206 * @param array $item
1208 * @return array with location array
1210 private static function createLocation($item)
1212 $location = ['type' => 'Place'];
1214 if (!empty($item['location'])) {
1215 $location['name'] = $item['location'];
1220 if (empty($item['coord'])) {
1221 $coord = Map::getCoordinates($item['location']);
1223 $coords = explode(' ', $item['coord']);
1224 if (count($coords) == 2) {
1225 $coord = ['lat' => $coords[0], 'lon' => $coords[1]];
1229 if (!empty($coord['lat']) && !empty($coord['lon'])) {
1230 $location['latitude'] = $coord['lat'];
1231 $location['longitude'] = $coord['lon'];
1238 * Returns a tag array for a given item array
1240 * @param array $item
1242 * @return array of tags
1243 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1245 private static function createTagList($item)
1249 $terms = Tag::getByURIId($item['uri-id'], [Tag::HASHTAG, Tag::MENTION, Tag::IMPLICIT_MENTION, Tag::EXCLUSIVE_MENTION]);
1250 foreach ($terms as $term) {
1251 if ($term['type'] == Tag::HASHTAG) {
1252 $url = DI::baseUrl() . '/search?tag=' . urlencode($term['name']);
1253 $tags[] = ['type' => 'Hashtag', 'href' => $url, 'name' => '#' . $term['name']];
1255 $contact = Contact::getByURL($term['url'], false, ['addr']);
1256 if (empty($contact)) {
1259 if (!empty($contact['addr'])) {
1260 $mention = '@' . $contact['addr'];
1262 $mention = '@' . $term['url'];
1265 $tags[] = ['type' => 'Mention', 'href' => $term['url'], 'name' => $mention];
1269 $announce = self::getAnnounceArray($item);
1270 // Mention the original author upon commented reshares
1271 if (!empty($announce['comment'])) {
1272 $tags[] = ['type' => 'Mention', 'href' => $announce['actor']['url'], 'name' => '@' . $announce['actor']['addr']];
1279 * Adds attachment data to the JSON document
1281 * @param array $item Data of the item that is to be posted
1282 * @param string $type Object type
1284 * @return array with attachment data
1285 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1287 private static function createAttachmentList($item, $type)
1291 $uriids = [$item['uri-id']];
1292 $shared = BBCode::fetchShareAttributes($item['body']);
1293 if (!empty($shared['guid'])) {
1294 $shared_item = Post::selectFirst(['uri-id'], ['guid' => $shared['guid']]);
1295 if (!empty($shared_item['uri-id'])) {
1296 $uriids[] = $shared_item['uri-id'];
1301 foreach ($uriids as $uriid) {
1302 foreach (Post\Media::getByURIId($uriid, [Post\Media::DOCUMENT, Post\Media::TORRENT]) 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;
1329 if ($type != 'Note') {
1330 return $attachments;
1333 foreach ($uriids as $uriid) {
1334 foreach (Post\Media::getByURIId($uriid, [Post\Media::AUDIO, Post\Media::IMAGE, Post\Media::VIDEO]) as $attachment) {
1335 if (in_array($attachment['url'], $urls)) {
1338 $urls[] = $attachment['url'];
1340 $attach = ['type' => 'Document',
1341 'mediaType' => $attachment['mimetype'],
1342 'url' => $attachment['url'],
1343 'name' => $attachment['description']];
1345 if (!empty($attachment['height'])) {
1346 $attach['height'] = $attachment['height'];
1349 if (!empty($attachment['width'])) {
1350 $attach['width'] = $attachment['width'];
1353 if (!empty($attachment['preview'])) {
1354 $attach['image'] = $attachment['preview'];
1357 $attachments[] = $attach;
1359 // Currently deactivated, since it creates side effects on Mastodon and Pleroma.
1360 // It will be activated, once this cleared.
1362 foreach (Post\Media::getByURIId($uriid, [Post\Media::HTML]) as $attachment) {
1363 if (in_array($attachment['url'], $urls)) {
1366 $urls[] = $attachment['url'];
1368 $attachments[] = ['type' => 'Page',
1369 'mediaType' => $attachment['mimetype'],
1370 'url' => $attachment['url'],
1371 'name' => $attachment['description']];
1375 return $attachments;
1379 * Callback function to replace a Friendica style mention in a mention for a summary
1381 * @param array $match Matching values for the callback
1382 * @return string Replaced mention
1383 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1385 private static function mentionAddrCallback($match)
1387 if (empty($match[1])) {
1391 $data = Contact::getByURL($match[1], false, ['addr']);
1392 if (empty($data['addr'])) {
1396 return '@' . $data['addr'];
1400 * Remove image elements since they are added as attachment
1402 * @param string $body
1404 * @return string with removed images
1406 private static function removePictures($body)
1408 // Simplify image codes
1409 $body = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '[img]$3[/img]', $body);
1410 $body = preg_replace("/\[img\=(.*?)\](.*?)\[\/img\]/ism", '[img]$1[/img]', $body);
1412 // Now remove local links
1413 $body = preg_replace_callback(
1414 '/\[url=([^\[\]]*)\]\[img\](.*)\[\/img\]\[\/url\]/Usi',
1416 // We remove the link when it is a link to a local photo page
1417 if (Photo::isLocalPage($match[1])) {
1420 // otherwise we just return the link
1421 return '[url]' . $match[1] . '[/url]';
1426 // Remove all pictures
1427 $body = preg_replace("/\[img\]([^\[\]]*)\[\/img\]/Usi", '', $body);
1433 * Fetches the "context" value for a givem item array from the "conversation" table
1435 * @param array $item
1437 * @return string with context url
1438 * @throws \Exception
1440 private static function fetchContextURLForItem($item)
1442 $conversation = DBA::selectFirst('conversation', ['conversation-href', 'conversation-uri'], ['item-uri' => $item['parent-uri']]);
1443 if (DBA::isResult($conversation) && !empty($conversation['conversation-href'])) {
1444 $context_uri = $conversation['conversation-href'];
1445 } elseif (DBA::isResult($conversation) && !empty($conversation['conversation-uri'])) {
1446 $context_uri = $conversation['conversation-uri'];
1448 $context_uri = $item['parent-uri'] . '#context';
1450 return $context_uri;
1454 * Returns if the post contains sensitive content ("nsfw")
1456 * @param integer $uri_id
1459 * @throws \Exception
1461 private static function isSensitive($uri_id)
1463 return DBA::exists('tag-view', ['uri-id' => $uri_id, 'name' => 'nsfw']);
1467 * Creates event data
1469 * @param array $item
1471 * @return array with the event data
1472 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1474 private static function createEvent($item)
1477 $event['name'] = $item['event-summary'];
1478 $event['content'] = BBCode::convertForUriId($item['uri-id'], $item['event-desc'], BBCode::ACTIVITYPUB);
1479 $event['startTime'] = DateTimeFormat::utc($item['event-start'], 'c');
1481 if (!$item['event-nofinish']) {
1482 $event['endTime'] = DateTimeFormat::utc($item['event-finish'], 'c');
1485 if (!empty($item['event-location'])) {
1486 $item['location'] = $item['event-location'];
1487 $event['location'] = self::createLocation($item);
1490 // 2021.12: Backward compatibility value, all the events now "adjust" to the viewer timezone
1491 $event['dfrn:adjust'] = true;
1497 * Creates a note/article object array
1499 * @param array $item
1501 * @return array with the object data
1502 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1503 * @throws \ImagickException
1505 public static function createNote($item)
1511 if ($item['event-type'] == 'event') {
1513 } elseif (!empty($item['title'])) {
1519 if ($item['deleted']) {
1520 $type = 'Tombstone';
1524 $data['id'] = $item['uri'];
1525 $data['type'] = $type;
1527 if ($item['deleted']) {
1531 $data['summary'] = BBCode::toPlaintext(BBCode::getAbstract($item['body'], Protocol::ACTIVITYPUB));
1533 if ($item['uri'] != $item['thr-parent']) {
1534 $data['inReplyTo'] = $item['thr-parent'];
1536 $data['inReplyTo'] = null;
1539 $data['diaspora:guid'] = $item['guid'];
1540 $data['published'] = DateTimeFormat::utc($item['created'] . '+00:00', DateTimeFormat::ATOM);
1542 if ($item['created'] != $item['edited']) {
1543 $data['updated'] = DateTimeFormat::utc($item['edited'] . '+00:00', DateTimeFormat::ATOM);
1546 $data['url'] = $item['plink'];
1547 $data['attributedTo'] = $item['author-link'];
1548 $data['sensitive'] = self::isSensitive($item['uri-id']);
1549 $data['context'] = self::fetchContextURLForItem($item);
1551 if (!empty($item['title'])) {
1552 $data['name'] = BBCode::toPlaintext($item['title'], false);
1555 $permission_block = self::createPermissionBlockForItem($item, false);
1557 $body = $item['body'];
1559 if ($type == 'Note') {
1560 $body = $item['raw-body'] ?? self::removePictures($body);
1564 * @todo Improve the automated summary
1565 * This part is currently deactivated. The automated summary seems to be more
1566 * confusing than helping. But possibly we will find a better way.
1567 * So the code is left here for now as a reminder
1569 * } elseif (($type == 'Article') && empty($data['summary'])) {
1570 * $regexp = "/[@!]\[url\=([^\[\]]*)\].*?\[\/url\]/ism";
1571 * $summary = preg_replace_callback($regexp, ['self', 'mentionAddrCallback'], $body);
1572 * $data['summary'] = BBCode::toPlaintext(Plaintext::shorten(self::removePictures($summary), 1000));
1576 if (empty($item['uid']) || !Feature::isEnabled($item['uid'], 'explicit_mentions')) {
1577 $body = self::prependMentions($body, $item['uri-id'], $item['author-link']);
1580 if ($type == 'Event') {
1581 $data = array_merge($data, self::createEvent($item));
1583 $body = BBCode::setMentionsToNicknames($body);
1585 $data['content'] = BBCode::convertForUriId($item['uri-id'], $body, BBCode::ACTIVITYPUB);
1588 // The regular "content" field does contain a minimized HTML. This is done since systems like
1589 // Mastodon has got problems with - for example - embedded pictures.
1590 // The contentMap does contain the unmodified HTML.
1591 $language = self::getLanguage($item);
1592 if (!empty($language)) {
1593 $richbody = BBCode::setMentionsToNicknames($item['body'] ?? '');
1594 $richbody = BBCode::removeAttachment($richbody);
1596 $data['contentMap'][$language] = BBCode::convertForUriId($item['uri-id'], $richbody, BBCode::EXTERNAL);
1599 $data['source'] = ['content' => $item['body'], 'mediaType' => "text/bbcode"];
1601 if (!empty($item['signed_text']) && ($item['uri'] != $item['thr-parent'])) {
1602 $data['diaspora:comment'] = $item['signed_text'];
1605 $data['attachment'] = self::createAttachmentList($item, $type);
1606 $data['tag'] = self::createTagList($item);
1608 if (empty($data['location']) && (!empty($item['coord']) || !empty($item['location']))) {
1609 $data['location'] = self::createLocation($item);
1612 if (!empty($item['app'])) {
1613 $data['generator'] = ['type' => 'Application', 'name' => $item['app']];
1616 $data = array_merge($data, $permission_block);
1622 * Fetches the language from the post, the user or the system.
1624 * @param array $item
1626 * @return string language string
1628 private static function getLanguage(array $item)
1630 // Try to fetch the language from the post itself
1631 if (!empty($item['language'])) {
1632 $languages = array_keys(json_decode($item['language'], true));
1633 if (!empty($languages[0])) {
1634 return $languages[0];
1638 // Otherwise use the user's language
1639 if (!empty($item['uid'])) {
1640 $user = DBA::selectFirst('user', ['language'], ['uid' => $item['uid']]);
1641 if (!empty($user['language'])) {
1642 return $user['language'];
1646 // And finally just use the system language
1647 return DI::config()->get('system', 'language');
1651 * Creates an an "add tag" entry
1653 * @param array $item
1654 * @param array $data activity data
1656 * @return array with activity data for adding tags
1657 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1658 * @throws \ImagickException
1660 private static function createAddTag($item, $data)
1662 $object = XML::parseString($item['object']);
1663 $target = XML::parseString($item["target"]);
1665 $data['diaspora:guid'] = $item['guid'];
1666 $data['actor'] = $item['author-link'];
1667 $data['target'] = (string)$target->id;
1668 $data['summary'] = BBCode::toPlaintext($item['body']);
1669 $data['object'] = ['id' => (string)$object->id, 'type' => 'tag', 'name' => (string)$object->title, 'content' => (string)$object->content];
1675 * Creates an announce object entry
1677 * @param array $item
1678 * @param array $data activity data
1680 * @return array with activity data
1681 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1682 * @throws \ImagickException
1684 private static function createAnnounce($item, $data)
1686 $orig_body = $item['body'];
1687 $announce = self::getAnnounceArray($item);
1688 if (empty($announce)) {
1689 $data['type'] = 'Create';
1690 $data['object'] = self::createNote($item);
1694 if (empty($announce['comment'])) {
1695 // Pure announce, without a quote
1696 $data['type'] = 'Announce';
1697 $data['object'] = $announce['object']['uri'];
1702 $data['type'] = 'Create';
1703 $item['body'] = $announce['comment'] . "\n" . $announce['object']['plink'];
1704 $data['object'] = self::createNote($item);
1706 /// @todo Finally descide how to implement this in AP. This is a possible way:
1707 $data['object']['attachment'][] = self::createNote($announce['object']);
1709 $data['object']['source']['content'] = $orig_body;
1714 * Return announce related data if the item is an annunce
1716 * @param array $item
1720 public static function getAnnounceArray($item)
1722 $reshared = Item::getShareArray($item);
1723 if (empty($reshared['guid'])) {
1727 $reshared_item = Post::selectFirst(Item::DELIVER_FIELDLIST, ['guid' => $reshared['guid']]);
1728 if (!DBA::isResult($reshared_item)) {
1732 if (!in_array($reshared_item['network'], [Protocol::ACTIVITYPUB, Protocol::DFRN])) {
1736 $profile = APContact::getByURL($reshared_item['author-link'], false);
1737 if (empty($profile)) {
1741 return ['object' => $reshared_item, 'actor' => $profile, 'comment' => $reshared['comment']];
1745 * Checks if the provided item array is an announce
1747 * @param array $item
1751 public static function isAnnounce($item)
1753 if (!empty($item['verb']) && ($item['verb'] == Activity::ANNOUNCE)) {
1757 $announce = self::getAnnounceArray($item);
1758 if (empty($announce)) {
1762 return empty($announce['comment']);
1766 * Creates an activity id for a given contact id
1768 * @param integer $cid Contact ID of target
1770 * @return bool|string activity id
1772 public static function activityIDFromContact($cid)
1774 $contact = DBA::selectFirst('contact', ['uid', 'id', 'created'], ['id' => $cid]);
1775 if (!DBA::isResult($contact)) {
1779 $hash = hash('ripemd128', $contact['uid'].'-'.$contact['id'].'-'.$contact['created']);
1780 $uuid = substr($hash, 0, 8). '-' . substr($hash, 8, 4) . '-' . substr($hash, 12, 4) . '-' . substr($hash, 16, 4) . '-' . substr($hash, 20, 12);
1781 return DI::baseUrl() . '/activity/' . $uuid;
1785 * Transmits a contact suggestion to a given inbox
1787 * @param integer $uid User ID
1788 * @param string $inbox Target inbox
1789 * @param integer $suggestion_id Suggestion ID
1791 * @return boolean was the transmission successful?
1792 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1794 public static function sendContactSuggestion($uid, $inbox, $suggestion_id)
1796 $owner = User::getOwnerDataById($uid);
1798 $suggestion = DI::fsuggest()->getById($suggestion_id);
1800 $data = ['@context' => ActivityPub::CONTEXT,
1801 'id' => DI::baseUrl() . '/activity/' . System::createGUID(),
1802 'type' => 'Announce',
1803 'actor' => $owner['url'],
1804 'object' => $suggestion->url,
1805 'content' => $suggestion->note,
1806 'instrument' => self::getService(),
1807 'to' => [ActivityPub::PUBLIC_COLLECTION],
1810 $signed = LDSignature::sign($data, $owner);
1812 Logger::log('Deliver profile deletion for user ' . $uid . ' to ' . $inbox . ' via ActivityPub', Logger::DEBUG);
1813 return HTTPSignature::transmit($signed, $inbox, $uid);
1817 * Transmits a profile relocation to a given inbox
1819 * @param integer $uid User ID
1820 * @param string $inbox Target inbox
1822 * @return boolean was the transmission successful?
1823 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1825 public static function sendProfileRelocation($uid, $inbox)
1827 $owner = User::getOwnerDataById($uid);
1829 $data = ['@context' => ActivityPub::CONTEXT,
1830 'id' => DI::baseUrl() . '/activity/' . System::createGUID(),
1831 'type' => 'dfrn:relocate',
1832 'actor' => $owner['url'],
1833 'object' => $owner['url'],
1834 'published' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
1835 'instrument' => self::getService(),
1836 'to' => [ActivityPub::PUBLIC_COLLECTION],
1839 $signed = LDSignature::sign($data, $owner);
1841 Logger::log('Deliver profile relocation for user ' . $uid . ' to ' . $inbox . ' via ActivityPub', Logger::DEBUG);
1842 return HTTPSignature::transmit($signed, $inbox, $uid);
1846 * Transmits a profile deletion to a given inbox
1848 * @param integer $uid User ID
1849 * @param string $inbox Target inbox
1851 * @return boolean was the transmission successful?
1852 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1854 public static function sendProfileDeletion($uid, $inbox)
1856 $owner = User::getOwnerDataById($uid);
1858 if (empty($owner)) {
1859 Logger::error('No owner data found, the deletion message cannot be processed.', ['user' => $uid]);
1863 if (empty($owner['uprvkey'])) {
1864 Logger::error('No private key for owner found, the deletion message cannot be processed.', ['user' => $uid]);
1868 $data = ['@context' => ActivityPub::CONTEXT,
1869 'id' => DI::baseUrl() . '/activity/' . System::createGUID(),
1871 'actor' => $owner['url'],
1872 'object' => $owner['url'],
1873 'published' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
1874 'instrument' => self::getService(),
1875 'to' => [ActivityPub::PUBLIC_COLLECTION],
1878 $signed = LDSignature::sign($data, $owner);
1880 Logger::log('Deliver profile deletion for user ' . $uid . ' to ' . $inbox . ' via ActivityPub', Logger::DEBUG);
1881 return HTTPSignature::transmit($signed, $inbox, $uid);
1885 * Transmits a profile change to a given inbox
1887 * @param integer $uid User ID
1888 * @param string $inbox Target inbox
1890 * @return boolean was the transmission successful?
1891 * @throws HTTPException\InternalServerErrorException
1892 * @throws HTTPException\NotFoundException
1893 * @throws \ImagickException
1895 public static function sendProfileUpdate(int $uid, string $inbox): bool
1897 $owner = User::getOwnerDataById($uid);
1898 $profile = APContact::getByURL($owner['url']);
1900 $data = ['@context' => ActivityPub::CONTEXT,
1901 'id' => DI::baseUrl() . '/activity/' . System::createGUID(),
1903 'actor' => $owner['url'],
1904 'object' => self::getProfile($uid),
1905 'published' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
1906 'instrument' => self::getService(),
1907 'to' => [$profile['followers']],
1910 $signed = LDSignature::sign($data, $owner);
1912 Logger::log('Deliver profile update for user ' . $uid . ' to ' . $inbox . ' via ActivityPub', Logger::DEBUG);
1913 return HTTPSignature::transmit($signed, $inbox, $uid);
1917 * Transmits a given activity to a target
1919 * @param string $activity Type name
1920 * @param string $target Target profile
1921 * @param integer $uid User ID
1923 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1924 * @throws \ImagickException
1925 * @throws \Exception
1927 public static function sendActivity($activity, $target, $uid, $id = '')
1929 $profile = APContact::getByURL($target);
1930 if (empty($profile['inbox'])) {
1931 Logger::warning('No inbox found for target', ['target' => $target, 'profile' => $profile]);
1935 $owner = User::getOwnerDataById($uid);
1938 $id = DI::baseUrl() . '/activity/' . System::createGUID();
1941 $data = ['@context' => ActivityPub::CONTEXT,
1943 'type' => $activity,
1944 'actor' => $owner['url'],
1945 'object' => $profile['url'],
1946 'instrument' => self::getService(),
1947 'to' => [$profile['url']]];
1949 Logger::log('Sending activity ' . $activity . ' to ' . $target . ' for user ' . $uid, Logger::DEBUG);
1951 $signed = LDSignature::sign($data, $owner);
1952 return HTTPSignature::transmit($signed, $profile['inbox'], $uid);
1956 * Transmits a "follow object" activity to a target
1957 * This is a preparation for sending automated "follow" requests when receiving "Announce" messages
1959 * @param string $object Object URL
1960 * @param string $target Target profile
1961 * @param integer $uid User ID
1963 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1964 * @throws \ImagickException
1965 * @throws \Exception
1967 public static function sendFollowObject($object, $target, $uid = 0)
1969 $profile = APContact::getByURL($target);
1970 if (empty($profile['inbox'])) {
1971 Logger::warning('No inbox found for target', ['target' => $target, 'profile' => $profile]);
1976 // Fetch the list of administrators
1977 $admin_mail = explode(',', str_replace(' ', '', DI::config()->get('config', 'admin_email')));
1979 // We need to use some user as a sender. It doesn't care who it will send. We will use an administrator account.
1980 $condition = ['verified' => true, 'blocked' => false, 'account_removed' => false, 'account_expired' => false, 'email' => $admin_mail];
1981 $first_user = DBA::selectFirst('user', ['uid'], $condition);
1982 $uid = $first_user['uid'];
1985 $condition = ['verb' => Activity::FOLLOW, 'uid' => 0, 'parent-uri' => $object,
1986 'author-id' => Contact::getPublicIdByUserId($uid)];
1987 if (Post::exists($condition)) {
1988 Logger::log('Follow for ' . $object . ' for user ' . $uid . ' does already exist.', Logger::DEBUG);
1992 $owner = User::getOwnerDataById($uid);
1994 $data = ['@context' => ActivityPub::CONTEXT,
1995 'id' => DI::baseUrl() . '/activity/' . System::createGUID(),
1997 'actor' => $owner['url'],
1998 'object' => $object,
1999 'instrument' => self::getService(),
2000 'to' => [$profile['url']]];
2002 Logger::log('Sending follow ' . $object . ' to ' . $target . ' for user ' . $uid, Logger::DEBUG);
2004 $signed = LDSignature::sign($data, $owner);
2005 return HTTPSignature::transmit($signed, $profile['inbox'], $uid);
2009 * Transmit a message that the contact request had been accepted
2011 * @param string $target Target profile
2013 * @param integer $uid User ID
2014 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2015 * @throws \ImagickException
2017 public static function sendContactAccept($target, $id, $uid)
2019 $profile = APContact::getByURL($target);
2020 if (empty($profile['inbox'])) {
2021 Logger::warning('No inbox found for target', ['target' => $target, 'profile' => $profile]);
2025 $owner = User::getOwnerDataById($uid);
2026 $data = ['@context' => ActivityPub::CONTEXT,
2027 'id' => DI::baseUrl() . '/activity/' . System::createGUID(),
2029 'actor' => $owner['url'],
2031 'id' => (string)$id,
2033 'actor' => $profile['url'],
2034 'object' => $owner['url']
2036 'instrument' => self::getService(),
2037 'to' => [$profile['url']]];
2039 Logger::debug('Sending accept to ' . $target . ' for user ' . $uid . ' with id ' . $id);
2041 $signed = LDSignature::sign($data, $owner);
2042 HTTPSignature::transmit($signed, $profile['inbox'], $uid);
2046 * Reject a contact request or terminates the contact relation
2048 * @param string $target Target profile
2050 * @param integer $uid User ID
2051 * @return bool Operation success
2052 * @throws HTTPException\InternalServerErrorException
2053 * @throws \ImagickException
2055 public static function sendContactReject($target, $id, $uid): bool
2057 $profile = APContact::getByURL($target);
2058 if (empty($profile['inbox'])) {
2059 Logger::warning('No inbox found for target', ['target' => $target, 'profile' => $profile]);
2063 $owner = User::getOwnerDataById($uid);
2064 $data = ['@context' => ActivityPub::CONTEXT,
2065 'id' => DI::baseUrl() . '/activity/' . System::createGUID(),
2067 'actor' => $owner['url'],
2069 'id' => (string)$id,
2071 'actor' => $profile['url'],
2072 'object' => $owner['url']
2074 'instrument' => self::getService(),
2075 'to' => [$profile['url']]];
2077 Logger::debug('Sending reject to ' . $target . ' for user ' . $uid . ' with id ' . $id);
2079 $signed = LDSignature::sign($data, $owner);
2080 return HTTPSignature::transmit($signed, $profile['inbox'], $uid);
2084 * Transmits a message that we don't want to follow this contact anymore
2086 * @param string $target Target profile
2087 * @param integer $uid User ID
2088 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2089 * @throws \ImagickException
2090 * @throws \Exception
2091 * @return bool success
2093 public static function sendContactUndo($target, $cid, $uid)
2095 $profile = APContact::getByURL($target);
2096 if (empty($profile['inbox'])) {
2097 Logger::warning('No inbox found for target', ['target' => $target, 'profile' => $profile]);
2101 $object_id = self::activityIDFromContact($cid);
2102 if (empty($object_id)) {
2106 $id = DI::baseUrl() . '/activity/' . System::createGUID();
2108 $owner = User::getOwnerDataById($uid);
2109 $data = ['@context' => ActivityPub::CONTEXT,
2112 'actor' => $owner['url'],
2113 'object' => ['id' => $object_id, 'type' => 'Follow',
2114 'actor' => $owner['url'],
2115 'object' => $profile['url']],
2116 'instrument' => self::getService(),
2117 'to' => [$profile['url']]];
2119 Logger::log('Sending undo to ' . $target . ' for user ' . $uid . ' with id ' . $id, Logger::DEBUG);
2121 $signed = LDSignature::sign($data, $owner);
2122 return HTTPSignature::transmit($signed, $profile['inbox'], $uid);
2125 private static function prependMentions($body, int $uriid, string $authorLink)
2129 foreach (Tag::getByURIId($uriid, [Tag::IMPLICIT_MENTION]) as $tag) {
2130 $profile = Contact::getByURL($tag['url'], false, ['addr', 'contact-type', 'nick']);
2131 if (!empty($profile['addr'])
2132 && $profile['contact-type'] != Contact::TYPE_COMMUNITY
2133 && !strstr($body, $profile['addr'])
2134 && !strstr($body, $tag['url'])
2135 && $tag['url'] !== $authorLink
2137 $mentions[] = '@[url=' . $tag['url'] . ']' . $profile['nick'] . '[/url]';
2141 $mentions[] = $body;
2143 return implode(' ', $mentions);