3 * @copyright Copyright (C) 2010-2021, the Friendica project
5 * @license GNU AGPL version 3 or any later version
7 * This program is free software: you can redistribute it and/or modify
8 * it under the terms of the GNU Affero General Public License as
9 * published by the Free Software Foundation, either version 3 of the
10 * License, or (at your option) any later version.
12 * This program is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU Affero General Public License for more details.
17 * You should have received a copy of the GNU Affero General Public License
18 * along with this program. If not, see <https://www.gnu.org/licenses/>.
22 namespace Friendica\Protocol\ActivityPub;
24 use Friendica\Content\Feature;
25 use Friendica\Content\Text\BBCode;
26 use Friendica\Content\Text\Plaintext;
27 use Friendica\Core\Cache\Duration;
28 use Friendica\Core\Logger;
29 use Friendica\Core\Protocol;
30 use Friendica\Core\System;
31 use Friendica\Database\DBA;
33 use Friendica\Model\APContact;
34 use Friendica\Model\Contact;
35 use Friendica\Model\Conversation;
36 use Friendica\Model\GServer;
37 use Friendica\Model\Item;
38 use Friendica\Model\ItemURI;
39 use Friendica\Model\Profile;
40 use Friendica\Model\Photo;
41 use Friendica\Model\Post;
42 use Friendica\Model\Tag;
43 use Friendica\Model\User;
44 use Friendica\Protocol\Activity;
45 use Friendica\Protocol\ActivityPub;
46 use Friendica\Protocol\Relay;
47 use Friendica\Util\DateTimeFormat;
48 use Friendica\Util\HTTPSignature;
49 use Friendica\Util\JsonLD;
50 use Friendica\Util\LDSignature;
51 use Friendica\Util\Map;
52 use Friendica\Util\Network;
53 use Friendica\Util\XML;
56 * ActivityPub Transmitter Protocol class
64 * Add relay servers to the list of inboxes
66 * @param array $inboxes
67 * @return array inboxes with added relay servers
69 public static function addRelayServerInboxes(array $inboxes = [])
71 foreach (Relay::getList(['inbox']) as $contact) {
72 $inboxes[$contact['inbox']] = $contact['inbox'];
79 * Add relay servers to the list of inboxes
81 * @param array $inboxes
82 * @return array inboxes with added relay servers
84 public static function addRelayServerInboxesForItem(int $item_id, array $inboxes = [])
86 $item = Post::selectFirst(['uid'], ['id' => $item_id]);
91 $relays = Relay::getDirectRelayList($item_id);
96 foreach ($relays as $relay) {
97 $contact = Contact::getByURLForUser($relay['url'], $item['uid'], false, ['id']);
98 $inboxes[$relay['batch']][] = $contact['id'] ?? 0;
104 * Subscribe to a relay
106 * @param string $url Subscribe actor url
107 * @return bool success
109 public static function sendRelayFollow(string $url)
111 $contact = Contact::getByURL($url);
112 if (empty($contact)) {
116 $activity_id = ActivityPub\Transmitter::activityIDFromContact($contact['id']);
117 $success = ActivityPub\Transmitter::sendActivity('Follow', $url, 0, $activity_id);
119 DBA::update('contact', ['rel' => Contact::FRIEND], ['id' => $contact['id']]);
126 * Unsubscribe from a relay
128 * @param string $url Subscribe actor url
129 * @param bool $force Set the relay status as non follower even if unsubscribe hadn't worked
130 * @return bool success
132 public static function sendRelayUndoFollow(string $url, bool $force = false)
134 $contact = Contact::getByURL($url);
135 if (empty($contact)) {
139 $success = self::sendContactUndo($url, $contact['id'], 0);
140 if ($success || $force) {
141 DBA::update('contact', ['rel' => Contact::NOTHING], ['id' => $contact['id']]);
148 * Collects a list of contacts of the given owner
150 * @param array $owner Owner array
151 * @param int|array $rel The relevant value(s) contact.rel should match
152 * @param string $module The name of the relevant AP endpoint module (followers|following)
153 * @param integer $page Page number
155 * @return array of owners
158 public static function getContacts($owner, $rel, $module, $page = null)
162 'uid' => $owner['uid'],
170 $condition = DBA::buildCondition($parameters);
172 $sql = "SELECT COUNT(*) as `count`
174 JOIN `apcontact` ON `apcontact`.`url` = `contact`.`url`
177 $contacts = DBA::fetchFirst($sql, ...$parameters);
179 $modulePath = '/' . $module . '/';
181 $data = ['@context' => ActivityPub::CONTEXT];
182 $data['id'] = DI::baseUrl() . $modulePath . $owner['nickname'];
183 $data['type'] = 'OrderedCollection';
184 $data['totalItems'] = $contacts['count'];
186 // When we hide our friends we will only show the pure number but don't allow more.
187 $profile = Profile::getByUID($owner['uid']);
188 if (!empty($profile['hide-friends'])) {
193 $data['first'] = DI::baseUrl() . $modulePath . $owner['nickname'] . '?page=1';
195 $data['type'] = 'OrderedCollectionPage';
198 $sql = "SELECT `contact`.`url`
200 JOIN `apcontact` ON `apcontact`.`url` = `contact`.`url`
204 $parameters[] = ($page - 1) * 100;
207 $contacts = DBA::p($sql, ...$parameters);
208 while ($contact = DBA::fetch($contacts)) {
209 $list[] = $contact['url'];
211 DBA::close($contacts);
214 $data['next'] = DI::baseUrl() . $modulePath . $owner['nickname'] . '?page=' . ($page + 1);
217 $data['partOf'] = DI::baseUrl() . $modulePath . $owner['nickname'];
219 $data['orderedItems'] = $list;
226 * Public posts for the given owner
228 * @param array $owner Owner array
229 * @param integer $page Page number
230 * @param string $requester URL of requesting account
232 * @return array of posts
233 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
234 * @throws \ImagickException
236 public static function getOutbox($owner, $page = null, $requester = '')
238 $public_contact = Contact::getIdForURL($owner['url']);
239 $condition = ['uid' => 0, 'contact-id' => $public_contact,
240 'private' => [Item::PUBLIC, Item::UNLISTED]];
242 if (!empty($requester)) {
243 $requester_id = Contact::getIdForURL($requester, $owner['uid']);
244 if (!empty($requester_id)) {
245 $permissionSets = DI::permissionSet()->selectByContactId($requester_id, $owner['uid']);
246 if (!empty($permissionSets)) {
247 $condition = ['uid' => $owner['uid'], 'origin' => true,
248 'psid' => array_merge($permissionSets->column('id'),
249 [DI::permissionSet()->getIdFromACL($owner['uid'], '', '', '', '')])];
254 $condition = array_merge($condition,
255 ['author-id' => $public_contact,
256 'gravity' => [GRAVITY_PARENT, GRAVITY_COMMENT],
257 'deleted' => false, 'visible' => true]);
259 $count = Post::count($condition);
261 $data = ['@context' => ActivityPub::CONTEXT];
262 $data['id'] = DI::baseUrl() . '/outbox/' . $owner['nickname'];
263 $data['type'] = 'OrderedCollection';
264 $data['totalItems'] = $count;
267 $data['first'] = DI::baseUrl() . '/outbox/' . $owner['nickname'] . '?page=1';
269 $data['type'] = 'OrderedCollectionPage';
272 $condition['parent-network'] = Protocol::NATIVE_SUPPORT;
274 $items = Post::select(['id'], $condition, ['limit' => [($page - 1) * 20, 20], 'order' => ['created' => true]]);
275 while ($item = Post::fetch($items)) {
276 $activity = self::createActivityFromItem($item['id'], true);
277 $activity['type'] = $activity['type'] == 'Update' ? 'Create' : $activity['type'];
279 // Only list "Create" activity objects here, no reshares
280 if (!empty($activity['object']) && ($activity['type'] == 'Create')) {
281 $list[] = $activity['object'];
287 $data['next'] = DI::baseUrl() . '/outbox/' . $owner['nickname'] . '?page=' . ($page + 1);
290 $data['partOf'] = DI::baseUrl() . '/outbox/' . $owner['nickname'];
292 $data['orderedItems'] = $list;
299 * Return the service array containing information the used software and it's url
301 * @return array with service data
303 private static function getService()
305 return ['type' => 'Service',
306 'name' => FRIENDICA_PLATFORM . " '" . FRIENDICA_CODENAME . "' " . FRIENDICA_VERSION . '-' . DB_UPDATE_VERSION,
307 'url' => DI::baseUrl()->get()];
311 * Return the ActivityPub profile of the given user
313 * @param integer $uid User ID
314 * @return array with profile data
315 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
317 public static function getProfile($uid)
320 $condition = ['uid' => $uid, 'blocked' => false, 'account_expired' => false,
321 'account_removed' => false, 'verified' => true];
322 $fields = ['guid', 'nickname', 'pubkey', 'account-type', 'page-flags'];
323 $user = DBA::selectFirst('user', $fields, $condition);
324 if (!DBA::isResult($user)) {
328 $fields = ['locality', 'region', 'country-name'];
329 $profile = DBA::selectFirst('profile', $fields, ['uid' => $uid]);
330 if (!DBA::isResult($profile)) {
334 $fields = ['name', 'url', 'location', 'about', 'avatar', 'photo'];
335 $contact = DBA::selectFirst('contact', $fields, ['uid' => $uid, 'self' => true]);
336 if (!DBA::isResult($contact)) {
340 $contact = User::getSystemAccount();
341 $user = ['guid' => '', 'nickname' => $contact['nick'], 'pubkey' => $contact['pubkey'],
342 'account-type' => $contact['contact-type'], 'page-flags' => User::PAGE_FLAGS_NORMAL];
343 $profile = ['locality' => '', 'region' => '', 'country-name' => ''];
346 $data = ['@context' => ActivityPub::CONTEXT];
347 $data['id'] = $contact['url'];
349 if (!empty($user['guid'])) {
350 $data['diaspora:guid'] = $user['guid'];
353 $data['type'] = ActivityPub::ACCOUNT_TYPES[$user['account-type']];
356 $data['following'] = DI::baseUrl() . '/following/' . $user['nickname'];
357 $data['followers'] = DI::baseUrl() . '/followers/' . $user['nickname'];
358 $data['inbox'] = DI::baseUrl() . '/inbox/' . $user['nickname'];
359 $data['outbox'] = DI::baseUrl() . '/outbox/' . $user['nickname'];
361 $data['inbox'] = DI::baseUrl() . '/friendica/inbox';
364 $data['preferredUsername'] = $user['nickname'];
365 $data['name'] = $contact['name'];
367 if (!empty($profile['country-name'] . $profile['region'] . $profile['locality'])) {
368 $data['vcard:hasAddress'] = ['@type' => 'vcard:Home', 'vcard:country-name' => $profile['country-name'],
369 'vcard:region' => $profile['region'], 'vcard:locality' => $profile['locality']];
372 if (!empty($contact['about'])) {
373 $data['summary'] = BBCode::convert($contact['about'], false);
376 $data['url'] = $contact['url'];
377 $data['manuallyApprovesFollowers'] = in_array($user['page-flags'], [User::PAGE_FLAGS_NORMAL, User::PAGE_FLAGS_PRVGROUP]);
378 $data['publicKey'] = ['id' => $contact['url'] . '#main-key',
379 'owner' => $contact['url'],
380 'publicKeyPem' => $user['pubkey']];
381 $data['endpoints'] = ['sharedInbox' => DI::baseUrl() . '/inbox'];
382 $data['icon'] = ['type' => 'Image', 'url' => $contact['photo']];
384 $resourceid = Photo::ridFromURI($contact['photo']);
385 if (!empty($resourceid)) {
386 $photo = Photo::selectFirst(['type'], ["resource-id" => $resourceid]);
387 if (!empty($photo['type'])) {
388 $data['icon']['mediaType'] = $photo['type'];
392 if (!empty($contact['header'])) {
393 $data['image'] = ['type' => 'Image', 'url' => $contact['header']];
395 $resourceid = Photo::ridFromURI($contact['header']);
396 if (!empty($resourceid)) {
397 $photo = Photo::selectFirst(['type'], ["resource-id" => $resourceid]);
398 if (!empty($photo['type'])) {
399 $data['image']['mediaType'] = $photo['type'];
404 $data['generator'] = self::getService();
406 // tags: https://kitty.town/@inmysocks/100656097926961126.json
411 * @param string $username
413 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
415 public static function getDeletedUser($username)
418 '@context' => ActivityPub::CONTEXT,
419 'id' => DI::baseUrl() . '/profile/' . $username,
420 'type' => 'Tombstone',
421 'published' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
422 'updated' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
423 'deleted' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
428 * Returns an array with permissions of a given item array
432 * @return array with permissions
433 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
434 * @throws \ImagickException
436 private static function fetchPermissionBlockFromConversation($item)
438 if (empty($item['thr-parent'])) {
442 $condition = ['item-uri' => $item['thr-parent'], 'protocol' => Conversation::PARCEL_ACTIVITYPUB];
443 $conversation = DBA::selectFirst('conversation', ['source'], $condition);
444 if (!DBA::isResult($conversation)) {
448 $activity = json_decode($conversation['source'], true);
450 $actor = JsonLD::fetchElement($activity, 'actor', 'id');
451 if (!empty($actor)) {
452 $permissions['to'][] = $actor;
453 $profile = APContact::getByURL($actor);
458 $item_profile = APContact::getByURL($item['author-link']);
459 $exclude[] = $item['author-link'];
461 if ($item['gravity'] == GRAVITY_PARENT) {
462 $exclude[] = $item['owner-link'];
465 foreach (['to', 'cc', 'bto', 'bcc'] as $element) {
466 if (empty($activity[$element])) {
469 if (is_string($activity[$element])) {
470 $activity[$element] = [$activity[$element]];
473 foreach ($activity[$element] as $receiver) {
474 if (empty($receiver)) {
478 if (!empty($profile['followers']) && $receiver == $profile['followers'] && !empty($item_profile['followers'])) {
479 $permissions[$element][] = $item_profile['followers'];
480 } elseif (!in_array($receiver, $exclude)) {
481 $permissions[$element][] = $receiver;
489 * Check if the given item id is from ActivityPub
491 * @param integer $item_id
492 * @return boolean "true" if the post is from ActivityPub
494 private static function isAPPost(int $item_id)
496 if (empty($item_id)) {
500 return Post::exists(['id' => $item_id, 'network' => Protocol::ACTIVITYPUB]);
504 * Creates an array of permissions from an item thread
506 * @param array $item Item array
507 * @param boolean $blindcopy addressing via "bcc" or "cc"?
508 * @param integer $last_id Last item id for adding receivers
509 * @param boolean $forum_mode "true" means that we are sending content to a forum
511 * @return array with permission data
512 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
513 * @throws \ImagickException
515 private static function createPermissionBlockForItem($item, $blindcopy, $last_id = 0, $forum_mode = false)
518 $last_id = $item['id'];
523 // Check if we should always deliver our stuff via BCC
524 if (!empty($item['uid'])) {
525 $profile = User::getOwnerDataById($item['uid']);
526 if (!empty($profile)) {
527 $always_bcc = $profile['hide-friends'];
531 if (DI::config()->get('system', 'ap_always_bcc')) {
535 if (self::isAnnounce($item) || DI::config()->get('debug', 'total_ap_delivery') || self::isAPPost($last_id)) {
536 // Will be activated in a later step
537 $networks = Protocol::FEDERATED;
539 // For now only send to these contacts:
540 $networks = [Protocol::ACTIVITYPUB, Protocol::OSTATUS];
543 $data = ['to' => [], 'cc' => [], 'bcc' => []];
545 if ($item['gravity'] == GRAVITY_PARENT) {
546 $actor_profile = APContact::getByURL($item['owner-link']);
548 $actor_profile = APContact::getByURL($item['author-link']);
553 $terms = Tag::getByURIId($item['uri-id'], [Tag::MENTION, Tag::IMPLICIT_MENTION, Tag::EXCLUSIVE_MENTION]);
555 if ($item['private'] != Item::PRIVATE) {
556 // Directly mention the original author upon a quoted reshare.
557 // Else just ensure that the original author receives the reshare.
558 $announce = self::getAnnounceArray($item);
559 if (!empty($announce['comment'])) {
560 $data['to'][] = $announce['actor']['url'];
561 } elseif (!empty($announce)) {
562 $data['cc'][] = $announce['actor']['url'];
565 $data = array_merge($data, self::fetchPermissionBlockFromConversation($item));
567 // Check if the item is completely public or unlisted
568 if ($item['private'] == Item::PUBLIC) {
569 $data['to'][] = ActivityPub::PUBLIC_COLLECTION;
571 $data['cc'][] = ActivityPub::PUBLIC_COLLECTION;
574 foreach ($terms as $term) {
575 $profile = APContact::getByURL($term['url'], false);
576 if (!empty($profile)) {
577 if ($term['type'] == Tag::EXCLUSIVE_MENTION) {
579 if (!empty($profile['followers']) && ($profile['type'] == 'Group')) {
580 $data['cc'][] = $profile['followers'];
583 $data['to'][] = $profile['url'];
587 $receiver_list = Item::enumeratePermissions($item, true);
589 foreach ($terms as $term) {
590 $cid = Contact::getIdForURL($term['url'], $item['uid']);
591 if (!empty($cid) && in_array($cid, $receiver_list)) {
592 $contact = DBA::selectFirst('contact', ['url', 'network', 'protocol', 'gsid'], ['id' => $cid, 'network' => Protocol::FEDERATED]);
593 if (!DBA::isResult($contact) || !self::isAPContact($contact, $networks)) {
597 if (!empty($profile = APContact::getByURL($contact['url'], false))) {
598 $data['to'][] = $profile['url'];
603 foreach ($receiver_list as $receiver) {
604 $contact = DBA::selectFirst('contact', ['url', 'hidden', 'network', 'protocol', 'gsid'], ['id' => $receiver, 'network' => Protocol::FEDERATED]);
605 if (!DBA::isResult($contact) || !self::isAPContact($contact, $networks)) {
609 if (!empty($profile = APContact::getByURL($contact['url'], false))) {
610 if ($contact['hidden'] || $always_bcc) {
611 $data['bcc'][] = $profile['url'];
613 $data['cc'][] = $profile['url'];
619 if (!empty($item['parent'])) {
620 $parents = Post::select(['id', 'author-link', 'owner-link', 'gravity', 'uri'], ['parent' => $item['parent']]);
621 while ($parent = Post::fetch($parents)) {
622 if ($parent['gravity'] == GRAVITY_PARENT) {
623 $profile = APContact::getByURL($parent['owner-link'], false);
624 if (!empty($profile)) {
625 if ($item['gravity'] != GRAVITY_PARENT) {
626 // Comments to forums are directed to the forum
627 // But comments to forums aren't directed to the followers collection
628 // This rule is only valid when the actor isn't the forum.
629 // The forum needs to transmit their content to their followers.
630 if (($profile['type'] == 'Group') && ($profile['url'] != ($actor_profile['url'] ?? ''))) {
631 $data['to'][] = $profile['url'];
633 $data['cc'][] = $profile['url'];
634 if (($item['private'] != Item::PRIVATE) && !empty($actor_profile['followers'])) {
635 $data['cc'][] = $actor_profile['followers'];
638 } elseif (!$exclusive) {
639 // Public thread parent post always are directed to the followers.
640 // This mustn't be done by posts that are directed to forum servers via the exclusive mention.
641 // But possibly in that case we could add the "followers" collection of the forum to the message.
642 if (($item['private'] != Item::PRIVATE) && !$forum_mode) {
643 $data['cc'][] = $actor_profile['followers'];
649 // Don't include data from future posts
650 if ($parent['id'] >= $last_id) {
654 $profile = APContact::getByURL($parent['author-link'], false);
655 if (!empty($profile)) {
656 if (($profile['type'] == 'Group') || ($parent['uri'] == $item['thr-parent'])) {
657 $data['to'][] = $profile['url'];
659 $data['cc'][] = $profile['url'];
663 DBA::close($parents);
666 $data['to'] = array_unique($data['to']);
667 $data['cc'] = array_unique($data['cc']);
668 $data['bcc'] = array_unique($data['bcc']);
670 if (($key = array_search($item['author-link'], $data['to'])) !== false) {
671 unset($data['to'][$key]);
674 if (($key = array_search($item['author-link'], $data['cc'])) !== false) {
675 unset($data['cc'][$key]);
678 if (($key = array_search($item['author-link'], $data['bcc'])) !== false) {
679 unset($data['bcc'][$key]);
682 foreach ($data['to'] as $to) {
683 if (($key = array_search($to, $data['cc'])) !== false) {
684 unset($data['cc'][$key]);
687 if (($key = array_search($to, $data['bcc'])) !== false) {
688 unset($data['bcc'][$key]);
692 foreach ($data['cc'] as $cc) {
693 if (($key = array_search($cc, $data['bcc'])) !== false) {
694 unset($data['bcc'][$key]);
698 $receivers = ['to' => array_values($data['to']), 'cc' => array_values($data['cc']), 'bcc' => array_values($data['bcc'])];
701 unset($receivers['bcc']);
708 * Check if an inbox is archived
710 * @param string $url Inbox url
712 * @return boolean "true" if inbox is archived
714 public static function archivedInbox($url)
716 return DBA::exists('inbox-status', ['url' => $url, 'archive' => true]);
720 * Check if a given contact should be delivered via AP
722 * @param array $contact
723 * @param array $networks
727 private static function isAPContact(array $contact, array $networks)
729 if (in_array($contact['network'], $networks) || ($contact['protocol'] == Protocol::ACTIVITYPUB)) {
733 return GServer::getProtocol($contact['gsid'] ?? 0) == Post\DeliveryData::ACTIVITYPUB;
737 * Fetches a list of inboxes of followers of a given user
739 * @param integer $uid User ID
740 * @param boolean $personal fetch personal inboxes
741 * @param boolean $all_ap Retrieve all AP enabled inboxes
743 * @return array of follower inboxes
744 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
745 * @throws \ImagickException
747 public static function fetchTargetInboxesforUser($uid, $personal = false, bool $all_ap = false)
753 if (!empty($item['uid'])) {
754 $profile = User::getOwnerDataById($item['uid']);
755 if (!empty($profile)) {
756 $isforum = $profile['account-type'] == User::ACCOUNT_TYPE_COMMUNITY;
760 if (DI::config()->get('debug', 'total_ap_delivery') || $all_ap) {
761 // Will be activated in a later step
762 $networks = Protocol::FEDERATED;
764 // For now only send to these contacts:
765 $networks = [Protocol::ACTIVITYPUB, Protocol::OSTATUS];
768 $condition = ['uid' => $uid, 'archive' => false, 'pending' => false, 'blocked' => false, 'network' => Protocol::FEDERATED];
771 $condition['rel'] = [Contact::FOLLOWER, Contact::FRIEND];
774 $contacts = DBA::select('contact', ['id', 'url', 'network', 'protocol', 'gsid'], $condition);
775 while ($contact = DBA::fetch($contacts)) {
776 if (!self::isAPContact($contact, $networks)) {
780 if ($isforum && ($contact['network'] == Protocol::DFRN)) {
784 if (Network::isUrlBlocked($contact['url'])) {
788 $profile = APContact::getByURL($contact['url'], false);
789 if (!empty($profile)) {
790 if (empty($profile['sharedinbox']) || $personal || Contact::isLocal($contact['url'])) {
791 $target = $profile['inbox'];
793 $target = $profile['sharedinbox'];
795 if (!self::archivedInbox($target)) {
796 $inboxes[$target][] = $contact['id'];
800 DBA::close($contacts);
806 * Fetches an array of inboxes for the given item and user
808 * @param array $item Item array
809 * @param integer $uid User ID
810 * @param boolean $personal fetch personal inboxes
811 * @param integer $last_id Last item id for adding receivers
812 * @param boolean $forum_mode "true" means that we are sending content to a forum
813 * @return array with inboxes
814 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
815 * @throws \ImagickException
817 public static function fetchTargetInboxes($item, $uid, $personal = false, $last_id = 0, $forum_mode = false)
819 $permissions = self::createPermissionBlockForItem($item, true, $last_id, $forum_mode);
820 if (empty($permissions)) {
826 if ($item['gravity'] == GRAVITY_ACTIVITY) {
827 $item_profile = APContact::getByURL($item['author-link'], false);
829 $item_profile = APContact::getByURL($item['owner-link'], false);
832 if (empty($item_profile)) {
836 $profile_uid = User::getIdForURL($item_profile['url']);
838 foreach (['to', 'cc', 'bto', 'bcc'] as $element) {
839 if (empty($permissions[$element])) {
843 $blindcopy = in_array($element, ['bto', 'bcc']);
845 foreach ($permissions[$element] as $receiver) {
846 if (empty($receiver) || Network::isUrlBlocked($receiver)) {
850 if ($item_profile && ($receiver == $item_profile['followers']) && ($uid == $profile_uid)) {
851 $inboxes = array_merge($inboxes, self::fetchTargetInboxesforUser($uid, $personal, self::isAPPost($last_id)));
853 $profile = APContact::getByURL($receiver, false);
854 if (!empty($profile)) {
855 $contact = Contact::getByURLForUser($receiver, $uid, false, ['id']);
857 if (empty($profile['sharedinbox']) || $personal || $blindcopy || Contact::isLocal($receiver)) {
858 $target = $profile['inbox'];
860 $target = $profile['sharedinbox'];
862 if (!self::archivedInbox($target)) {
863 $inboxes[$target][] = $contact['id'] ?? 0;
874 * Creates an array in the structure of the item table for a given mail id
876 * @param integer $mail_id
881 public static function ItemArrayFromMail($mail_id, $use_title = false)
883 $mail = DBA::selectFirst('mail', [], ['id' => $mail_id]);
884 if (!DBA::isResult($mail)) {
888 $reply = DBA::selectFirst('mail', ['uri', 'uri-id', 'from-url'], ['parent-uri' => $mail['parent-uri'], 'reply' => false]);
890 // Making the post more compatible for Mastodon by:
891 // - Making it a note and not an article (no title)
892 // - Moving the title into the "summary" field that is used as a "content warning"
895 $mail['body'] = '[abstract]' . $mail['title'] . "[/abstract]\n" . $mail['body'];
899 $mail['author-link'] = $mail['owner-link'] = $mail['from-url'];
900 $mail['owner-id'] = $mail['author-id'];
901 $mail['allow_cid'] = '<'.$mail['contact-id'].'>';
902 $mail['allow_gid'] = '';
903 $mail['deny_cid'] = '';
904 $mail['deny_gid'] = '';
905 $mail['private'] = Item::PRIVATE;
906 $mail['deleted'] = false;
907 $mail['edited'] = $mail['created'];
908 $mail['plink'] = DI::baseUrl() . '/message/' . $mail['id'];
909 $mail['parent-uri'] = $reply['uri'];
910 $mail['parent-uri-id'] = $reply['uri-id'];
911 $mail['parent-author-id'] = Contact::getIdForURL($reply['from-url'], 0, false);
912 $mail['gravity'] = ($mail['reply'] ? GRAVITY_COMMENT: GRAVITY_PARENT);
913 $mail['event-type'] = '';
914 $mail['language'] = '';
921 * Creates an activity array for a given mail id
923 * @param integer $mail_id
924 * @param boolean $object_mode Is the activity item is used inside another object?
926 * @return array of activity
929 public static function createActivityFromMail($mail_id, $object_mode = false)
931 $mail = self::ItemArrayFromMail($mail_id);
935 $object = self::createNote($mail);
938 $data = ['@context' => ActivityPub::CONTEXT];
943 $data['id'] = $mail['uri'] . '/Create';
944 $data['type'] = 'Create';
945 $data['actor'] = $mail['author-link'];
946 $data['published'] = DateTimeFormat::utc($mail['created'] . '+00:00', DateTimeFormat::ATOM);
947 $data['instrument'] = self::getService();
948 $data = array_merge($data, self::createPermissionBlockForItem($mail, true));
950 if (empty($data['to']) && !empty($data['cc'])) {
951 $data['to'] = $data['cc'];
954 if (empty($data['to']) && !empty($data['bcc'])) {
955 $data['to'] = $data['bcc'];
961 $object['to'] = $data['to'];
962 $object['tag'] = [['type' => 'Mention', 'href' => $object['to'][0], 'name' => '']];
964 unset($object['cc']);
965 unset($object['bcc']);
967 $data['directMessage'] = true;
969 $data['object'] = $object;
971 $owner = User::getOwnerDataById($mail['uid']);
973 if (!$object_mode && !empty($owner)) {
974 return LDSignature::sign($data, $owner);
981 * Returns the activity type of a given item
985 * @return string with activity type
986 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
987 * @throws \ImagickException
989 private static function getTypeOfItem($item)
993 // Only check for a reshare, if it is a real reshare and no quoted reshare
994 if (strpos($item['body'], "[share") === 0) {
995 $announce = self::getAnnounceArray($item);
996 $reshared = !empty($announce);
1001 } elseif ($item['verb'] == Activity::POST) {
1002 if ($item['created'] == $item['edited']) {
1007 } elseif ($item['verb'] == Activity::LIKE) {
1009 } elseif ($item['verb'] == Activity::DISLIKE) {
1011 } elseif ($item['verb'] == Activity::ATTEND) {
1013 } elseif ($item['verb'] == Activity::ATTENDNO) {
1015 } elseif ($item['verb'] == Activity::ATTENDMAYBE) {
1016 $type = 'TentativeAccept';
1017 } elseif ($item['verb'] == Activity::FOLLOW) {
1019 } elseif ($item['verb'] == Activity::TAG) {
1021 } elseif ($item['verb'] == Activity::ANNOUNCE) {
1031 * Creates the activity or fetches it from the cache
1033 * @param integer $item_id
1034 * @param boolean $force Force new cache entry
1036 * @return array with the activity
1037 * @throws \Exception
1039 public static function createCachedActivityFromItem($item_id, $force = false)
1041 $cachekey = 'APDelivery:createActivity:' . $item_id;
1044 $data = DI::cache()->get($cachekey);
1045 if (!is_null($data)) {
1050 $data = self::createActivityFromItem($item_id);
1052 DI::cache()->set($cachekey, $data, Duration::QUARTER_HOUR);
1057 * Creates an activity array for a given item id
1059 * @param integer $item_id
1060 * @param boolean $object_mode Is the activity item is used inside another object?
1062 * @return false|array
1063 * @throws \Exception
1065 public static function createActivityFromItem(int $item_id, bool $object_mode = false)
1067 Logger::info('Fetching activity', ['item' => $item_id]);
1068 $item = Post::selectFirst(Item::DELIVER_FIELDLIST, ['id' => $item_id, 'parent-network' => Protocol::NATIVE_SUPPORT]);
1069 if (!DBA::isResult($item)) {
1073 // In case of a forum post ensure to return the original post if author and forum are on the same machine
1074 if (($item['gravity'] == GRAVITY_PARENT) && !empty($item['forum_mode'])) {
1075 $author = Contact::getById($item['author-id'], ['nurl']);
1076 if (!empty($author['nurl'])) {
1077 $self = Contact::selectFirst(['uid'], ['nurl' => $author['nurl'], 'self' => true]);
1078 if (!empty($self['uid'])) {
1079 $forum_item = Post::selectFirst(Item::DELIVER_FIELDLIST, ['uri-id' => $item['uri-id'], 'uid' => $self['uid']]);
1080 if (DBA::isResult($forum_item)) {
1081 $item = $forum_item;
1087 if (empty($item['uri-id'])) {
1088 Logger::warning('Item without uri-id', ['item' => $item]);
1092 if (!$item['deleted']) {
1093 $condition = ['item-uri' => $item['uri'], 'protocol' => Conversation::PARCEL_ACTIVITYPUB];
1094 $conversation = DBA::selectFirst('conversation', ['source'], $condition);
1095 if (!$item['origin'] && DBA::isResult($conversation)) {
1096 $data = json_decode($conversation['source'], true);
1097 if (!empty($data['type'])) {
1098 if (in_array($data['type'], ['Create', 'Update'])) {
1100 unset($data['@context']);
1101 unset($data['signature']);
1103 Logger::info('Return stored conversation', ['item' => $item_id]);
1105 } elseif (in_array('as:' . $data['type'], Receiver::CONTENT_TYPES)) {
1106 if (!empty($data['@context'])) {
1107 $context = $data['@context'];
1108 unset($data['@context']);
1110 unset($data['actor']);
1117 $type = self::getTypeOfItem($item);
1119 if (!$object_mode) {
1120 $data = ['@context' => $context ?? ActivityPub::CONTEXT];
1122 if ($item['deleted'] && ($item['gravity'] == GRAVITY_ACTIVITY)) {
1124 } elseif ($item['deleted']) {
1131 if ($type == 'Delete') {
1132 $data['id'] = Item::newURI($item['uid'], $item['guid']) . '/' . $type;;
1133 } elseif (($item['gravity'] == GRAVITY_ACTIVITY) && ($type != 'Undo')) {
1134 $data['id'] = $item['uri'];
1136 $data['id'] = $item['uri'] . '/' . $type;
1139 $data['type'] = $type;
1141 if (($type != 'Announce') || ($item['gravity'] != GRAVITY_PARENT)) {
1142 $data['actor'] = $item['author-link'];
1144 $data['actor'] = $item['owner-link'];
1147 $data['published'] = DateTimeFormat::utc($item['created'] . '+00:00', DateTimeFormat::ATOM);
1149 $data['instrument'] = self::getService();
1151 $data = array_merge($data, self::createPermissionBlockForItem($item, false));
1153 if (in_array($data['type'], ['Create', 'Update', 'Delete'])) {
1154 $data['object'] = $object ?? self::createNote($item);
1155 } elseif ($data['type'] == 'Add') {
1156 $data = self::createAddTag($item, $data);
1157 } elseif ($data['type'] == 'Announce') {
1158 if ($item['verb'] == ACTIVITY::ANNOUNCE) {
1159 $data['object'] = $item['thr-parent'];
1161 $data = self::createAnnounce($item, $data);
1163 } elseif ($data['type'] == 'Follow') {
1164 $data['object'] = $item['parent-uri'];
1165 } elseif ($data['type'] == 'Undo') {
1166 $data['object'] = self::createActivityFromItem($item_id, true);
1168 $data['diaspora:guid'] = $item['guid'];
1169 if (!empty($item['signed_text'])) {
1170 $data['diaspora:like'] = $item['signed_text'];
1172 $data['object'] = $item['thr-parent'];
1175 if (!empty($item['contact-uid'])) {
1176 $uid = $item['contact-uid'];
1178 $uid = $item['uid'];
1181 $owner = User::getOwnerDataById($uid);
1183 Logger::info('Fetched activity', ['item' => $item_id, 'uid' => $uid]);
1185 // We don't sign if we aren't the actor. This is important for relaying content especially for forums
1186 if (!$object_mode && !empty($owner) && ($data['actor'] == $owner['url'])) {
1187 return LDSignature::sign($data, $owner);
1192 /// @todo Create "conversation" entry
1196 * Creates a location entry for a given item array
1198 * @param array $item
1200 * @return array with location array
1202 private static function createLocation($item)
1204 $location = ['type' => 'Place'];
1206 if (!empty($item['location'])) {
1207 $location['name'] = $item['location'];
1212 if (empty($item['coord'])) {
1213 $coord = Map::getCoordinates($item['location']);
1215 $coords = explode(' ', $item['coord']);
1216 if (count($coords) == 2) {
1217 $coord = ['lat' => $coords[0], 'lon' => $coords[1]];
1221 if (!empty($coord['lat']) && !empty($coord['lon'])) {
1222 $location['latitude'] = $coord['lat'];
1223 $location['longitude'] = $coord['lon'];
1230 * Returns a tag array for a given item array
1232 * @param array $item
1234 * @return array of tags
1235 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1237 private static function createTagList($item)
1241 $terms = Tag::getByURIId($item['uri-id'], [Tag::HASHTAG, Tag::MENTION, Tag::IMPLICIT_MENTION, Tag::EXCLUSIVE_MENTION]);
1242 foreach ($terms as $term) {
1243 if ($term['type'] == Tag::HASHTAG) {
1244 $url = DI::baseUrl() . '/search?tag=' . urlencode($term['name']);
1245 $tags[] = ['type' => 'Hashtag', 'href' => $url, 'name' => '#' . $term['name']];
1247 $contact = Contact::getByURL($term['url'], false, ['addr']);
1248 if (empty($contact)) {
1251 if (!empty($contact['addr'])) {
1252 $mention = '@' . $contact['addr'];
1254 $mention = '@' . $term['url'];
1257 $tags[] = ['type' => 'Mention', 'href' => $term['url'], 'name' => $mention];
1261 $announce = self::getAnnounceArray($item);
1262 // Mention the original author upon commented reshares
1263 if (!empty($announce['comment'])) {
1264 $tags[] = ['type' => 'Mention', 'href' => $announce['actor']['url'], 'name' => '@' . $announce['actor']['addr']];
1271 * Adds attachment data to the JSON document
1273 * @param array $item Data of the item that is to be posted
1274 * @param string $type Object type
1276 * @return array with attachment data
1277 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1279 private static function createAttachmentList($item, $type)
1283 $uriids = [$item['uri-id']];
1284 $shared = BBCode::fetchShareAttributes($item['body']);
1285 if (!empty($shared['guid'])) {
1286 $shared_item = Post::selectFirst(['uri-id'], ['guid' => $shared['guid']]);
1287 if (!empty($shared_item['uri-id'])) {
1288 $uriids[] = $shared_item['uri-id'];
1293 foreach ($uriids as $uriid) {
1294 foreach (Post\Media::getByURIId($uriid, [Post\Media::DOCUMENT, Post\Media::TORRENT]) as $attachment) {
1295 if (in_array($attachment['url'], $urls)) {
1298 $urls[] = $attachment['url'];
1300 $attachments[] = ['type' => 'Document',
1301 'mediaType' => $attachment['mimetype'],
1302 'url' => $attachment['url'],
1303 'name' => $attachment['description']];
1307 if ($type != 'Note') {
1308 return $attachments;
1311 foreach ($uriids as $uriid) {
1312 foreach (Post\Media::getByURIId($uriid, [Post\Media::AUDIO, Post\Media::IMAGE, Post\Media::VIDEO]) as $attachment) {
1313 if (in_array($attachment['url'], $urls)) {
1316 $urls[] = $attachment['url'];
1318 $attachments[] = ['type' => 'Document',
1319 'mediaType' => $attachment['mimetype'],
1320 'url' => $attachment['url'],
1321 'name' => $attachment['description']];
1323 // Currently deactivated, since it creates side effects on Mastodon and Pleroma.
1324 // It will be activated, once this cleared.
1326 foreach (Post\Media::getByURIId($uriid, [Post\Media::HTML]) as $attachment) {
1327 if (in_array($attachment['url'], $urls)) {
1330 $urls[] = $attachment['url'];
1332 $attachments[] = ['type' => 'Page',
1333 'mediaType' => $attachment['mimetype'],
1334 'url' => $attachment['url'],
1335 'name' => $attachment['description']];
1339 return $attachments;
1343 * Callback function to replace a Friendica style mention in a mention that is used on AP
1345 * @param array $match Matching values for the callback
1346 * @return string Replaced mention
1347 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1349 private static function mentionCallback($match)
1351 if (empty($match[1])) {
1355 $data = Contact::getByURL($match[1], false, ['url', 'alias', 'nick']);
1356 if (empty($data['nick'])) {
1360 return '[url=' . $data['url'] . ']@' . $data['nick'] . '[/url]';
1364 * Callback function to replace a Friendica style mention in a mention for a summary
1366 * @param array $match Matching values for the callback
1367 * @return string Replaced mention
1368 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1370 private static function mentionAddrCallback($match)
1372 if (empty($match[1])) {
1376 $data = Contact::getByURL($match[1], false, ['addr']);
1377 if (empty($data['addr'])) {
1381 return '@' . $data['addr'];
1385 * Remove image elements since they are added as attachment
1387 * @param string $body
1389 * @return string with removed images
1391 private static function removePictures($body)
1393 // Simplify image codes
1394 $body = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '[img]$3[/img]', $body);
1395 $body = preg_replace("/\[img\=(.*?)\](.*?)\[\/img\]/ism", '[img]$1[/img]', $body);
1397 // Now remove local links
1398 $body = preg_replace_callback(
1399 '/\[url=([^\[\]]*)\]\[img\](.*)\[\/img\]\[\/url\]/Usi',
1401 // We remove the link when it is a link to a local photo page
1402 if (Photo::isLocalPage($match[1])) {
1405 // otherwise we just return the link
1406 return '[url]' . $match[1] . '[/url]';
1411 // Remove all pictures
1412 $body = preg_replace("/\[img\]([^\[\]]*)\[\/img\]/Usi", '', $body);
1418 * Fetches the "context" value for a givem item array from the "conversation" table
1420 * @param array $item
1422 * @return string with context url
1423 * @throws \Exception
1425 private static function fetchContextURLForItem($item)
1427 $conversation = DBA::selectFirst('conversation', ['conversation-href', 'conversation-uri'], ['item-uri' => $item['parent-uri']]);
1428 if (DBA::isResult($conversation) && !empty($conversation['conversation-href'])) {
1429 $context_uri = $conversation['conversation-href'];
1430 } elseif (DBA::isResult($conversation) && !empty($conversation['conversation-uri'])) {
1431 $context_uri = $conversation['conversation-uri'];
1433 $context_uri = $item['parent-uri'] . '#context';
1435 return $context_uri;
1439 * Returns if the post contains sensitive content ("nsfw")
1441 * @param integer $uri_id
1444 * @throws \Exception
1446 private static function isSensitive($uri_id)
1448 return DBA::exists('tag-view', ['uri-id' => $uri_id, 'name' => 'nsfw']);
1452 * Creates event data
1454 * @param array $item
1456 * @return array with the event data
1457 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1459 private static function createEvent($item)
1462 $event['name'] = $item['event-summary'];
1463 $event['content'] = BBCode::convert($item['event-desc'], false, BBCode::ACTIVITYPUB);
1464 $event['startTime'] = DateTimeFormat::utc($item['event-start'] . '+00:00', DateTimeFormat::ATOM);
1466 if (!$item['event-nofinish']) {
1467 $event['endTime'] = DateTimeFormat::utc($item['event-finish'] . '+00:00', DateTimeFormat::ATOM);
1470 if (!empty($item['event-location'])) {
1471 $item['location'] = $item['event-location'];
1472 $event['location'] = self::createLocation($item);
1475 $event['dfrn:adjust'] = (bool)$item['event-adjust'];
1481 * Creates a note/article object array
1483 * @param array $item
1485 * @return array with the object data
1486 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1487 * @throws \ImagickException
1489 public static function createNote($item)
1495 if ($item['event-type'] == 'event') {
1497 } elseif (!empty($item['title'])) {
1503 if ($item['deleted']) {
1504 $type = 'Tombstone';
1508 $data['id'] = $item['uri'];
1509 $data['type'] = $type;
1511 if ($item['deleted']) {
1515 $data['summary'] = BBCode::toPlaintext(BBCode::getAbstract($item['body'], Protocol::ACTIVITYPUB));
1517 if ($item['uri'] != $item['thr-parent']) {
1518 $data['inReplyTo'] = $item['thr-parent'];
1520 $data['inReplyTo'] = null;
1523 $data['diaspora:guid'] = $item['guid'];
1524 $data['published'] = DateTimeFormat::utc($item['created'] . '+00:00', DateTimeFormat::ATOM);
1526 if ($item['created'] != $item['edited']) {
1527 $data['updated'] = DateTimeFormat::utc($item['edited'] . '+00:00', DateTimeFormat::ATOM);
1530 $data['url'] = $item['plink'];
1531 $data['attributedTo'] = $item['author-link'];
1532 $data['sensitive'] = self::isSensitive($item['uri-id']);
1533 $data['context'] = self::fetchContextURLForItem($item);
1535 if (!empty($item['title'])) {
1536 $data['name'] = BBCode::toPlaintext($item['title'], false);
1539 $permission_block = self::createPermissionBlockForItem($item, false);
1541 $body = $item['body'];
1543 if ($type == 'Note') {
1544 $body = $item['raw-body'] ?? self::removePictures($body);
1548 * @todo Improve the automated summary
1549 * This part is currently deactivated. The automated summary seems to be more
1550 * confusing than helping. But possibly we will find a better way.
1551 * So the code is left here for now as a reminder
1553 * } elseif (($type == 'Article') && empty($data['summary'])) {
1554 * $regexp = "/[@!]\[url\=([^\[\]]*)\].*?\[\/url\]/ism";
1555 * $summary = preg_replace_callback($regexp, ['self', 'mentionAddrCallback'], $body);
1556 * $data['summary'] = BBCode::toPlaintext(Plaintext::shorten(self::removePictures($summary), 1000));
1560 if (empty($item['uid']) || !Feature::isEnabled($item['uid'], 'explicit_mentions')) {
1561 $body = self::prependMentions($body, $item['uri-id'], $item['author-link']);
1564 if ($type == 'Event') {
1565 $data = array_merge($data, self::createEvent($item));
1567 $regexp = "/[@!]\[url\=([^\[\]]*)\].*?\[\/url\]/ism";
1568 $body = preg_replace_callback($regexp, ['self', 'mentionCallback'], $body);
1570 $data['content'] = BBCode::convert($body, false, BBCode::ACTIVITYPUB);
1573 // The regular "content" field does contain a minimized HTML. This is done since systems like
1574 // Mastodon has got problems with - for example - embedded pictures.
1575 // The contentMap does contain the unmodified HTML.
1576 $language = self::getLanguage($item);
1577 if (!empty($language)) {
1578 $regexp = "/[@!]\[url\=([^\[\]]*)\].*?\[\/url\]/ism";
1579 $richbody = preg_replace_callback($regexp, ['self', 'mentionCallback'], $item['body']);
1580 $richbody = BBCode::removeAttachment($richbody);
1582 $data['contentMap'][$language] = BBCode::convert($richbody, false, BBCode::EXTERNAL);
1585 $data['source'] = ['content' => $item['body'], 'mediaType' => "text/bbcode"];
1587 if (!empty($item['signed_text']) && ($item['uri'] != $item['thr-parent'])) {
1588 $data['diaspora:comment'] = $item['signed_text'];
1591 $data['attachment'] = self::createAttachmentList($item, $type);
1592 $data['tag'] = self::createTagList($item);
1594 if (empty($data['location']) && (!empty($item['coord']) || !empty($item['location']))) {
1595 $data['location'] = self::createLocation($item);
1598 if (!empty($item['app'])) {
1599 $data['generator'] = ['type' => 'Application', 'name' => $item['app']];
1602 $data = array_merge($data, $permission_block);
1608 * Fetches the language from the post, the user or the system.
1610 * @param array $item
1612 * @return string language string
1614 private static function getLanguage(array $item)
1616 // Try to fetch the language from the post itself
1617 if (!empty($item['language'])) {
1618 $languages = array_keys(json_decode($item['language'], true));
1619 if (!empty($languages[0])) {
1620 return $languages[0];
1624 // Otherwise use the user's language
1625 if (!empty($item['uid'])) {
1626 $user = DBA::selectFirst('user', ['language'], ['uid' => $item['uid']]);
1627 if (!empty($user['language'])) {
1628 return $user['language'];
1632 // And finally just use the system language
1633 return DI::config()->get('system', 'language');
1637 * Creates an an "add tag" entry
1639 * @param array $item
1640 * @param array $data activity data
1642 * @return array with activity data for adding tags
1643 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1644 * @throws \ImagickException
1646 private static function createAddTag($item, $data)
1648 $object = XML::parseString($item['object']);
1649 $target = XML::parseString($item["target"]);
1651 $data['diaspora:guid'] = $item['guid'];
1652 $data['actor'] = $item['author-link'];
1653 $data['target'] = (string)$target->id;
1654 $data['summary'] = BBCode::toPlaintext($item['body']);
1655 $data['object'] = ['id' => (string)$object->id, 'type' => 'tag', 'name' => (string)$object->title, 'content' => (string)$object->content];
1661 * Creates an announce object entry
1663 * @param array $item
1664 * @param array $data activity data
1666 * @return array with activity data
1667 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1668 * @throws \ImagickException
1670 private static function createAnnounce($item, $data)
1672 $orig_body = $item['body'];
1673 $announce = self::getAnnounceArray($item);
1674 if (empty($announce)) {
1675 $data['type'] = 'Create';
1676 $data['object'] = self::createNote($item);
1680 if (empty($announce['comment'])) {
1681 // Pure announce, without a quote
1682 $data['type'] = 'Announce';
1683 $data['object'] = $announce['object']['uri'];
1688 $data['type'] = 'Create';
1689 $item['body'] = $announce['comment'] . "\n" . $announce['object']['plink'];
1690 $data['object'] = self::createNote($item);
1692 /// @todo Finally descide how to implement this in AP. This is a possible way:
1693 $data['object']['attachment'][] = self::createNote($announce['object']);
1695 $data['object']['source']['content'] = $orig_body;
1700 * Return announce related data if the item is an annunce
1702 * @param array $item
1706 public static function getAnnounceArray($item)
1708 $reshared = Item::getShareArray($item);
1709 if (empty($reshared['guid'])) {
1713 $reshared_item = Post::selectFirst(Item::DELIVER_FIELDLIST, ['guid' => $reshared['guid']]);
1714 if (!DBA::isResult($reshared_item)) {
1718 if (!in_array($reshared_item['network'], [Protocol::ACTIVITYPUB, Protocol::DFRN])) {
1722 $profile = APContact::getByURL($reshared_item['author-link'], false);
1723 if (empty($profile)) {
1727 return ['object' => $reshared_item, 'actor' => $profile, 'comment' => $reshared['comment']];
1731 * Checks if the provided item array is an announce
1733 * @param array $item
1737 public static function isAnnounce($item)
1739 if (!empty($item['verb']) && ($item['verb'] == Activity::ANNOUNCE)) {
1743 $announce = self::getAnnounceArray($item);
1744 if (empty($announce)) {
1748 return empty($announce['comment']);
1752 * Creates an activity id for a given contact id
1754 * @param integer $cid Contact ID of target
1756 * @return bool|string activity id
1758 public static function activityIDFromContact($cid)
1760 $contact = DBA::selectFirst('contact', ['uid', 'id', 'created'], ['id' => $cid]);
1761 if (!DBA::isResult($contact)) {
1765 $hash = hash('ripemd128', $contact['uid'].'-'.$contact['id'].'-'.$contact['created']);
1766 $uuid = substr($hash, 0, 8). '-' . substr($hash, 8, 4) . '-' . substr($hash, 12, 4) . '-' . substr($hash, 16, 4) . '-' . substr($hash, 20, 12);
1767 return DI::baseUrl() . '/activity/' . $uuid;
1771 * Transmits a contact suggestion to a given inbox
1773 * @param integer $uid User ID
1774 * @param string $inbox Target inbox
1775 * @param integer $suggestion_id Suggestion ID
1777 * @return boolean was the transmission successful?
1778 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1780 public static function sendContactSuggestion($uid, $inbox, $suggestion_id)
1782 $owner = User::getOwnerDataById($uid);
1784 $suggestion = DI::fsuggest()->getById($suggestion_id);
1786 $data = ['@context' => ActivityPub::CONTEXT,
1787 'id' => DI::baseUrl() . '/activity/' . System::createGUID(),
1788 'type' => 'Announce',
1789 'actor' => $owner['url'],
1790 'object' => $suggestion->url,
1791 'content' => $suggestion->note,
1792 'instrument' => self::getService(),
1793 'to' => [ActivityPub::PUBLIC_COLLECTION],
1796 $signed = LDSignature::sign($data, $owner);
1798 Logger::log('Deliver profile deletion for user ' . $uid . ' to ' . $inbox . ' via ActivityPub', Logger::DEBUG);
1799 return HTTPSignature::transmit($signed, $inbox, $uid);
1803 * Transmits a profile relocation to a given inbox
1805 * @param integer $uid User ID
1806 * @param string $inbox Target inbox
1808 * @return boolean was the transmission successful?
1809 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1811 public static function sendProfileRelocation($uid, $inbox)
1813 $owner = User::getOwnerDataById($uid);
1815 $data = ['@context' => ActivityPub::CONTEXT,
1816 'id' => DI::baseUrl() . '/activity/' . System::createGUID(),
1817 'type' => 'dfrn:relocate',
1818 'actor' => $owner['url'],
1819 'object' => $owner['url'],
1820 'published' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
1821 'instrument' => self::getService(),
1822 'to' => [ActivityPub::PUBLIC_COLLECTION],
1825 $signed = LDSignature::sign($data, $owner);
1827 Logger::log('Deliver profile relocation for user ' . $uid . ' to ' . $inbox . ' via ActivityPub', Logger::DEBUG);
1828 return HTTPSignature::transmit($signed, $inbox, $uid);
1832 * Transmits a profile deletion to a given inbox
1834 * @param integer $uid User ID
1835 * @param string $inbox Target inbox
1837 * @return boolean was the transmission successful?
1838 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1840 public static function sendProfileDeletion($uid, $inbox)
1842 $owner = User::getOwnerDataById($uid);
1844 if (empty($owner)) {
1845 Logger::error('No owner data found, the deletion message cannot be processed.', ['user' => $uid]);
1849 if (empty($owner['uprvkey'])) {
1850 Logger::error('No private key for owner found, the deletion message cannot be processed.', ['user' => $uid]);
1854 $data = ['@context' => ActivityPub::CONTEXT,
1855 'id' => DI::baseUrl() . '/activity/' . System::createGUID(),
1857 'actor' => $owner['url'],
1858 'object' => $owner['url'],
1859 'published' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
1860 'instrument' => self::getService(),
1861 'to' => [ActivityPub::PUBLIC_COLLECTION],
1864 $signed = LDSignature::sign($data, $owner);
1866 Logger::log('Deliver profile deletion for user ' . $uid . ' to ' . $inbox . ' via ActivityPub', Logger::DEBUG);
1867 return HTTPSignature::transmit($signed, $inbox, $uid);
1871 * Transmits a profile change to a given inbox
1873 * @param integer $uid User ID
1874 * @param string $inbox Target inbox
1876 * @return boolean was the transmission successful?
1877 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1878 * @throws \ImagickException
1880 public static function sendProfileUpdate($uid, $inbox)
1882 $owner = User::getOwnerDataById($uid);
1883 $profile = APContact::getByURL($owner['url']);
1885 $data = ['@context' => ActivityPub::CONTEXT,
1886 'id' => DI::baseUrl() . '/activity/' . System::createGUID(),
1888 'actor' => $owner['url'],
1889 'object' => self::getProfile($uid),
1890 'published' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
1891 'instrument' => self::getService(),
1892 'to' => [$profile['followers']],
1895 $signed = LDSignature::sign($data, $owner);
1897 Logger::log('Deliver profile update for user ' . $uid . ' to ' . $inbox . ' via ActivityPub', Logger::DEBUG);
1898 return HTTPSignature::transmit($signed, $inbox, $uid);
1902 * Transmits a given activity to a target
1904 * @param string $activity Type name
1905 * @param string $target Target profile
1906 * @param integer $uid User ID
1908 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1909 * @throws \ImagickException
1910 * @throws \Exception
1912 public static function sendActivity($activity, $target, $uid, $id = '')
1914 $profile = APContact::getByURL($target);
1915 if (empty($profile['inbox'])) {
1916 Logger::warning('No inbox found for target', ['target' => $target, 'profile' => $profile]);
1920 $owner = User::getOwnerDataById($uid);
1923 $id = DI::baseUrl() . '/activity/' . System::createGUID();
1926 $data = ['@context' => ActivityPub::CONTEXT,
1928 'type' => $activity,
1929 'actor' => $owner['url'],
1930 'object' => $profile['url'],
1931 'instrument' => self::getService(),
1932 'to' => [$profile['url']]];
1934 Logger::log('Sending activity ' . $activity . ' to ' . $target . ' for user ' . $uid, Logger::DEBUG);
1936 $signed = LDSignature::sign($data, $owner);
1937 return HTTPSignature::transmit($signed, $profile['inbox'], $uid);
1941 * Transmits a "follow object" activity to a target
1942 * This is a preparation for sending automated "follow" requests when receiving "Announce" messages
1944 * @param string $object Object URL
1945 * @param string $target Target profile
1946 * @param integer $uid User ID
1948 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1949 * @throws \ImagickException
1950 * @throws \Exception
1952 public static function sendFollowObject($object, $target, $uid = 0)
1954 $profile = APContact::getByURL($target);
1955 if (empty($profile['inbox'])) {
1956 Logger::warning('No inbox found for target', ['target' => $target, 'profile' => $profile]);
1961 // Fetch the list of administrators
1962 $admin_mail = explode(',', str_replace(' ', '', DI::config()->get('config', 'admin_email')));
1964 // We need to use some user as a sender. It doesn't care who it will send. We will use an administrator account.
1965 $condition = ['verified' => true, 'blocked' => false, 'account_removed' => false, 'account_expired' => false, 'email' => $admin_mail];
1966 $first_user = DBA::selectFirst('user', ['uid'], $condition);
1967 $uid = $first_user['uid'];
1970 $condition = ['verb' => Activity::FOLLOW, 'uid' => 0, 'parent-uri' => $object,
1971 'author-id' => Contact::getPublicIdByUserId($uid)];
1972 if (Post::exists($condition)) {
1973 Logger::log('Follow for ' . $object . ' for user ' . $uid . ' does already exist.', Logger::DEBUG);
1977 $owner = User::getOwnerDataById($uid);
1979 $data = ['@context' => ActivityPub::CONTEXT,
1980 'id' => DI::baseUrl() . '/activity/' . System::createGUID(),
1982 'actor' => $owner['url'],
1983 'object' => $object,
1984 'instrument' => self::getService(),
1985 'to' => [$profile['url']]];
1987 Logger::log('Sending follow ' . $object . ' to ' . $target . ' for user ' . $uid, Logger::DEBUG);
1989 $signed = LDSignature::sign($data, $owner);
1990 return HTTPSignature::transmit($signed, $profile['inbox'], $uid);
1994 * Transmit a message that the contact request had been accepted
1996 * @param string $target Target profile
1998 * @param integer $uid User ID
1999 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2000 * @throws \ImagickException
2002 public static function sendContactAccept($target, $id, $uid)
2004 $profile = APContact::getByURL($target);
2005 if (empty($profile['inbox'])) {
2006 Logger::warning('No inbox found for target', ['target' => $target, 'profile' => $profile]);
2010 $owner = User::getOwnerDataById($uid);
2011 $data = ['@context' => ActivityPub::CONTEXT,
2012 'id' => DI::baseUrl() . '/activity/' . System::createGUID(),
2014 'actor' => $owner['url'],
2016 'id' => (string)$id,
2018 'actor' => $profile['url'],
2019 'object' => $owner['url']
2021 'instrument' => self::getService(),
2022 'to' => [$profile['url']]];
2024 Logger::debug('Sending accept to ' . $target . ' for user ' . $uid . ' with id ' . $id);
2026 $signed = LDSignature::sign($data, $owner);
2027 HTTPSignature::transmit($signed, $profile['inbox'], $uid);
2031 * Reject a contact request or terminates the contact relation
2033 * @param string $target Target profile
2035 * @param integer $uid User ID
2036 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2037 * @throws \ImagickException
2039 public static function sendContactReject($target, $id, $uid)
2041 $profile = APContact::getByURL($target);
2042 if (empty($profile['inbox'])) {
2043 Logger::warning('No inbox found for target', ['target' => $target, 'profile' => $profile]);
2047 $owner = User::getOwnerDataById($uid);
2048 $data = ['@context' => ActivityPub::CONTEXT,
2049 'id' => DI::baseUrl() . '/activity/' . System::createGUID(),
2051 'actor' => $owner['url'],
2053 'id' => (string)$id,
2055 'actor' => $profile['url'],
2056 'object' => $owner['url']
2058 'instrument' => self::getService(),
2059 'to' => [$profile['url']]];
2061 Logger::debug('Sending reject to ' . $target . ' for user ' . $uid . ' with id ' . $id);
2063 $signed = LDSignature::sign($data, $owner);
2064 HTTPSignature::transmit($signed, $profile['inbox'], $uid);
2068 * Transmits a message that we don't want to follow this contact anymore
2070 * @param string $target Target profile
2071 * @param integer $uid User ID
2072 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2073 * @throws \ImagickException
2074 * @throws \Exception
2075 * @return bool success
2077 public static function sendContactUndo($target, $cid, $uid)
2079 $profile = APContact::getByURL($target);
2080 if (empty($profile['inbox'])) {
2081 Logger::warning('No inbox found for target', ['target' => $target, 'profile' => $profile]);
2085 $object_id = self::activityIDFromContact($cid);
2086 if (empty($object_id)) {
2090 $id = DI::baseUrl() . '/activity/' . System::createGUID();
2092 $owner = User::getOwnerDataById($uid);
2093 $data = ['@context' => ActivityPub::CONTEXT,
2096 'actor' => $owner['url'],
2097 'object' => ['id' => $object_id, 'type' => 'Follow',
2098 'actor' => $owner['url'],
2099 'object' => $profile['url']],
2100 'instrument' => self::getService(),
2101 'to' => [$profile['url']]];
2103 Logger::log('Sending undo to ' . $target . ' for user ' . $uid . ' with id ' . $id, Logger::DEBUG);
2105 $signed = LDSignature::sign($data, $owner);
2106 return HTTPSignature::transmit($signed, $profile['inbox'], $uid);
2109 private static function prependMentions($body, int $uriid, string $authorLink)
2113 foreach (Tag::getByURIId($uriid, [Tag::IMPLICIT_MENTION]) as $tag) {
2114 $profile = Contact::getByURL($tag['url'], false, ['addr', 'contact-type', 'nick']);
2115 if (!empty($profile['addr'])
2116 && $profile['contact-type'] != Contact::TYPE_COMMUNITY
2117 && !strstr($body, $profile['addr'])
2118 && !strstr($body, $tag['url'])
2119 && $tag['url'] !== $authorLink
2121 $mentions[] = '@[url=' . $tag['url'] . ']' . $profile['nick'] . '[/url]';
2125 $mentions[] = $body;
2127 return implode(' ', $mentions);