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)
319 $owner = User::getOwnerDataById($uid);
321 $data = ['@context' => ActivityPub::CONTEXT];
322 $data['id'] = $owner['url'];
324 if (!empty($owner['guid'])) {
325 $data['diaspora:guid'] = $owner['guid'];
328 $data['type'] = ActivityPub::ACCOUNT_TYPES[$owner['account-type']];
331 $data['following'] = DI::baseUrl() . '/following/' . $owner['nick'];
332 $data['followers'] = DI::baseUrl() . '/followers/' . $owner['nick'];
333 $data['inbox'] = DI::baseUrl() . '/inbox/' . $owner['nick'];
334 $data['outbox'] = DI::baseUrl() . '/outbox/' . $owner['nick'];
336 $data['inbox'] = DI::baseUrl() . '/friendica/inbox';
339 $data['preferredUsername'] = $owner['nick'];
340 $data['name'] = $owner['name'];
342 if (!empty($owner['country-name'] . $owner['region'] . $owner['locality'])) {
343 $data['vcard:hasAddress'] = ['@type' => 'vcard:Home', 'vcard:country-name' => $owner['country-name'],
344 'vcard:region' => $owner['region'], 'vcard:locality' => $owner['locality']];
347 if (!empty($owner['about'])) {
348 $data['summary'] = BBCode::convert($owner['about'], false);
351 $data['url'] = $owner['url'];
352 $data['manuallyApprovesFollowers'] = in_array($owner['page-flags'], [User::PAGE_FLAGS_NORMAL, User::PAGE_FLAGS_PRVGROUP]);
353 $data['discoverable'] = $owner['net-publish'];
354 $data['publicKey'] = ['id' => $owner['url'] . '#main-key',
355 'owner' => $owner['url'],
356 'publicKeyPem' => $owner['pubkey']];
357 $data['endpoints'] = ['sharedInbox' => DI::baseUrl() . '/inbox'];
358 $data['icon'] = ['type' => 'Image', 'url' => Contact::getAvatarUrlForId($owner['id'], '', $owner['updated'])];
360 $resourceid = Photo::ridFromURI($owner['photo']);
361 if (!empty($resourceid)) {
362 $photo = Photo::selectFirst(['type'], ["resource-id" => $resourceid]);
363 if (!empty($photo['type'])) {
364 $data['icon']['mediaType'] = $photo['type'];
368 if (!empty($owner['header'])) {
369 $data['image'] = ['type' => 'Image', 'url' => Contact::getHeaderUrlForId($owner['id'], '', $owner['updated'])];
371 $resourceid = Photo::ridFromURI($owner['header']);
372 if (!empty($resourceid)) {
373 $photo = Photo::selectFirst(['type'], ["resource-id" => $resourceid]);
374 if (!empty($photo['type'])) {
375 $data['image']['mediaType'] = $photo['type'];
380 $data['generator'] = self::getService();
382 // tags: https://kitty.town/@inmysocks/100656097926961126.json
387 * @param string $username
389 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
391 public static function getDeletedUser($username)
394 '@context' => ActivityPub::CONTEXT,
395 'id' => DI::baseUrl() . '/profile/' . $username,
396 'type' => 'Tombstone',
397 'published' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
398 'updated' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
399 'deleted' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
404 * Returns an array with permissions of a given item array
408 * @return array with permissions
409 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
410 * @throws \ImagickException
412 private static function fetchPermissionBlockFromConversation($item)
414 if (empty($item['thr-parent'])) {
418 $condition = ['item-uri' => $item['thr-parent'], 'protocol' => Conversation::PARCEL_ACTIVITYPUB];
419 $conversation = DBA::selectFirst('conversation', ['source'], $condition);
420 if (!DBA::isResult($conversation)) {
424 $activity = json_decode($conversation['source'], true);
426 $actor = JsonLD::fetchElement($activity, 'actor', 'id');
427 if (!empty($actor)) {
428 $permissions['to'][] = $actor;
429 $profile = APContact::getByURL($actor);
434 $item_profile = APContact::getByURL($item['author-link']);
435 $exclude[] = $item['author-link'];
437 if ($item['gravity'] == GRAVITY_PARENT) {
438 $exclude[] = $item['owner-link'];
441 foreach (['to', 'cc', 'bto', 'bcc'] as $element) {
442 if (empty($activity[$element])) {
445 if (is_string($activity[$element])) {
446 $activity[$element] = [$activity[$element]];
449 foreach ($activity[$element] as $receiver) {
450 if (empty($receiver)) {
454 if (!empty($profile['followers']) && $receiver == $profile['followers'] && !empty($item_profile['followers'])) {
455 $permissions[$element][] = $item_profile['followers'];
456 } elseif (!in_array($receiver, $exclude)) {
457 $permissions[$element][] = $receiver;
465 * Check if the given item id is from ActivityPub
467 * @param integer $item_id
468 * @return boolean "true" if the post is from ActivityPub
470 private static function isAPPost(int $item_id)
472 if (empty($item_id)) {
476 return Post::exists(['id' => $item_id, 'network' => Protocol::ACTIVITYPUB]);
480 * Creates an array of permissions from an item thread
482 * @param array $item Item array
483 * @param boolean $blindcopy addressing via "bcc" or "cc"?
484 * @param integer $last_id Last item id for adding receivers
485 * @param boolean $forum_mode "true" means that we are sending content to a forum
487 * @return array with permission data
488 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
489 * @throws \ImagickException
491 private static function createPermissionBlockForItem($item, $blindcopy, $last_id = 0, $forum_mode = false)
494 $last_id = $item['id'];
499 // Check if we should always deliver our stuff via BCC
500 if (!empty($item['uid'])) {
501 $profile = User::getOwnerDataById($item['uid']);
502 if (!empty($profile)) {
503 $always_bcc = $profile['hide-friends'];
507 if (DI::config()->get('system', 'ap_always_bcc')) {
511 if (self::isAnnounce($item) || DI::config()->get('debug', 'total_ap_delivery') || self::isAPPost($last_id)) {
512 // Will be activated in a later step
513 $networks = Protocol::FEDERATED;
515 // For now only send to these contacts:
516 $networks = [Protocol::ACTIVITYPUB, Protocol::OSTATUS];
519 $data = ['to' => [], 'cc' => [], 'bcc' => []];
521 if ($item['gravity'] == GRAVITY_PARENT) {
522 $actor_profile = APContact::getByURL($item['owner-link']);
524 $actor_profile = APContact::getByURL($item['author-link']);
529 $terms = Tag::getByURIId($item['uri-id'], [Tag::MENTION, Tag::IMPLICIT_MENTION, Tag::EXCLUSIVE_MENTION]);
531 if ($item['private'] != Item::PRIVATE) {
532 // Directly mention the original author upon a quoted reshare.
533 // Else just ensure that the original author receives the reshare.
534 $announce = self::getAnnounceArray($item);
535 if (!empty($announce['comment'])) {
536 $data['to'][] = $announce['actor']['url'];
537 } elseif (!empty($announce)) {
538 $data['cc'][] = $announce['actor']['url'];
541 $data = array_merge($data, self::fetchPermissionBlockFromConversation($item));
543 // Check if the item is completely public or unlisted
544 if ($item['private'] == Item::PUBLIC) {
545 $data['to'][] = ActivityPub::PUBLIC_COLLECTION;
547 $data['cc'][] = ActivityPub::PUBLIC_COLLECTION;
550 foreach ($terms as $term) {
551 $profile = APContact::getByURL($term['url'], false);
552 if (!empty($profile)) {
553 if ($term['type'] == Tag::EXCLUSIVE_MENTION) {
555 if (!empty($profile['followers']) && ($profile['type'] == 'Group')) {
556 $data['cc'][] = $profile['followers'];
559 $data['to'][] = $profile['url'];
563 $receiver_list = Item::enumeratePermissions($item, true);
565 foreach ($terms as $term) {
566 $cid = Contact::getIdForURL($term['url'], $item['uid']);
567 if (!empty($cid) && in_array($cid, $receiver_list)) {
568 $contact = DBA::selectFirst('contact', ['url', 'network', 'protocol', 'gsid'], ['id' => $cid, 'network' => Protocol::FEDERATED]);
569 if (!DBA::isResult($contact) || !self::isAPContact($contact, $networks)) {
573 if (!empty($profile = APContact::getByURL($contact['url'], false))) {
574 $data['to'][] = $profile['url'];
579 foreach ($receiver_list as $receiver) {
580 $contact = DBA::selectFirst('contact', ['url', 'hidden', 'network', 'protocol', 'gsid'], ['id' => $receiver, 'network' => Protocol::FEDERATED]);
581 if (!DBA::isResult($contact) || !self::isAPContact($contact, $networks)) {
585 if (!empty($profile = APContact::getByURL($contact['url'], false))) {
586 if ($contact['hidden'] || $always_bcc) {
587 $data['bcc'][] = $profile['url'];
589 $data['cc'][] = $profile['url'];
595 if (!empty($item['parent'])) {
596 $parents = Post::select(['id', 'author-link', 'owner-link', 'gravity', 'uri'], ['parent' => $item['parent']]);
597 while ($parent = Post::fetch($parents)) {
598 if ($parent['gravity'] == GRAVITY_PARENT) {
599 $profile = APContact::getByURL($parent['owner-link'], false);
600 if (!empty($profile)) {
601 if ($item['gravity'] != GRAVITY_PARENT) {
602 // Comments to forums are directed to the forum
603 // But comments to forums aren't directed to the followers collection
604 // This rule is only valid when the actor isn't the forum.
605 // The forum needs to transmit their content to their followers.
606 if (($profile['type'] == 'Group') && ($profile['url'] != ($actor_profile['url'] ?? ''))) {
607 $data['to'][] = $profile['url'];
609 $data['cc'][] = $profile['url'];
610 if (($item['private'] != Item::PRIVATE) && !empty($actor_profile['followers'])) {
611 $data['cc'][] = $actor_profile['followers'];
614 } elseif (!$exclusive) {
615 // Public thread parent post always are directed to the followers.
616 // This mustn't be done by posts that are directed to forum servers via the exclusive mention.
617 // But possibly in that case we could add the "followers" collection of the forum to the message.
618 if (($item['private'] != Item::PRIVATE) && !$forum_mode) {
619 $data['cc'][] = $actor_profile['followers'];
625 // Don't include data from future posts
626 if ($parent['id'] >= $last_id) {
630 $profile = APContact::getByURL($parent['author-link'], false);
631 if (!empty($profile)) {
632 if (($profile['type'] == 'Group') || ($parent['uri'] == $item['thr-parent'])) {
633 $data['to'][] = $profile['url'];
635 $data['cc'][] = $profile['url'];
639 DBA::close($parents);
642 $data['to'] = array_unique($data['to']);
643 $data['cc'] = array_unique($data['cc']);
644 $data['bcc'] = array_unique($data['bcc']);
646 if (($key = array_search($item['author-link'], $data['to'])) !== false) {
647 unset($data['to'][$key]);
650 if (($key = array_search($item['author-link'], $data['cc'])) !== false) {
651 unset($data['cc'][$key]);
654 if (($key = array_search($item['author-link'], $data['bcc'])) !== false) {
655 unset($data['bcc'][$key]);
658 foreach ($data['to'] as $to) {
659 if (($key = array_search($to, $data['cc'])) !== false) {
660 unset($data['cc'][$key]);
663 if (($key = array_search($to, $data['bcc'])) !== false) {
664 unset($data['bcc'][$key]);
668 foreach ($data['cc'] as $cc) {
669 if (($key = array_search($cc, $data['bcc'])) !== false) {
670 unset($data['bcc'][$key]);
674 $receivers = ['to' => array_values($data['to']), 'cc' => array_values($data['cc']), 'bcc' => array_values($data['bcc'])];
677 unset($receivers['bcc']);
684 * Check if an inbox is archived
686 * @param string $url Inbox url
688 * @return boolean "true" if inbox is archived
690 public static function archivedInbox($url)
692 return DBA::exists('inbox-status', ['url' => $url, 'archive' => true]);
696 * Check if a given contact should be delivered via AP
698 * @param array $contact
699 * @param array $networks
703 private static function isAPContact(array $contact, array $networks)
705 if (in_array($contact['network'], $networks) || ($contact['protocol'] == Protocol::ACTIVITYPUB)) {
709 return GServer::getProtocol($contact['gsid'] ?? 0) == Post\DeliveryData::ACTIVITYPUB;
713 * Fetches a list of inboxes of followers of a given user
715 * @param integer $uid User ID
716 * @param boolean $personal fetch personal inboxes
717 * @param boolean $all_ap Retrieve all AP enabled inboxes
719 * @return array of follower inboxes
720 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
721 * @throws \ImagickException
723 public static function fetchTargetInboxesforUser($uid, $personal = false, bool $all_ap = false)
729 if (!empty($item['uid'])) {
730 $profile = User::getOwnerDataById($item['uid']);
731 if (!empty($profile)) {
732 $isforum = $profile['account-type'] == User::ACCOUNT_TYPE_COMMUNITY;
736 if (DI::config()->get('debug', 'total_ap_delivery') || $all_ap) {
737 // Will be activated in a later step
738 $networks = Protocol::FEDERATED;
740 // For now only send to these contacts:
741 $networks = [Protocol::ACTIVITYPUB, Protocol::OSTATUS];
744 $condition = ['uid' => $uid, 'archive' => false, 'pending' => false, 'blocked' => false, 'network' => Protocol::FEDERATED];
747 $condition['rel'] = [Contact::FOLLOWER, Contact::FRIEND];
750 $contacts = DBA::select('contact', ['id', 'url', 'network', 'protocol', 'gsid'], $condition);
751 while ($contact = DBA::fetch($contacts)) {
752 if (!self::isAPContact($contact, $networks)) {
756 if ($isforum && ($contact['network'] == Protocol::DFRN)) {
760 if (Network::isUrlBlocked($contact['url'])) {
764 $profile = APContact::getByURL($contact['url'], false);
765 if (!empty($profile)) {
766 if (empty($profile['sharedinbox']) || $personal || Contact::isLocal($contact['url'])) {
767 $target = $profile['inbox'];
769 $target = $profile['sharedinbox'];
771 if (!self::archivedInbox($target)) {
772 $inboxes[$target][] = $contact['id'];
776 DBA::close($contacts);
782 * Fetches an array of inboxes for the given item and user
784 * @param array $item Item array
785 * @param integer $uid User ID
786 * @param boolean $personal fetch personal inboxes
787 * @param integer $last_id Last item id for adding receivers
788 * @param boolean $forum_mode "true" means that we are sending content to a forum
789 * @return array with inboxes
790 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
791 * @throws \ImagickException
793 public static function fetchTargetInboxes($item, $uid, $personal = false, $last_id = 0, $forum_mode = false)
795 $permissions = self::createPermissionBlockForItem($item, true, $last_id, $forum_mode);
796 if (empty($permissions)) {
802 if ($item['gravity'] == GRAVITY_ACTIVITY) {
803 $item_profile = APContact::getByURL($item['author-link'], false);
805 $item_profile = APContact::getByURL($item['owner-link'], false);
808 if (empty($item_profile)) {
812 $profile_uid = User::getIdForURL($item_profile['url']);
814 foreach (['to', 'cc', 'bto', 'bcc'] as $element) {
815 if (empty($permissions[$element])) {
819 $blindcopy = in_array($element, ['bto', 'bcc']);
821 foreach ($permissions[$element] as $receiver) {
822 if (empty($receiver) || Network::isUrlBlocked($receiver)) {
826 if ($item_profile && ($receiver == $item_profile['followers']) && ($uid == $profile_uid)) {
827 $inboxes = array_merge($inboxes, self::fetchTargetInboxesforUser($uid, $personal, self::isAPPost($last_id)));
829 $profile = APContact::getByURL($receiver, false);
830 if (!empty($profile)) {
831 $contact = Contact::getByURLForUser($receiver, $uid, false, ['id']);
833 if (empty($profile['sharedinbox']) || $personal || $blindcopy || Contact::isLocal($receiver)) {
834 $target = $profile['inbox'];
836 $target = $profile['sharedinbox'];
838 if (!self::archivedInbox($target)) {
839 $inboxes[$target][] = $contact['id'] ?? 0;
850 * Creates an array in the structure of the item table for a given mail id
852 * @param integer $mail_id
857 public static function ItemArrayFromMail($mail_id, $use_title = false)
859 $mail = DBA::selectFirst('mail', [], ['id' => $mail_id]);
860 if (!DBA::isResult($mail)) {
864 $reply = DBA::selectFirst('mail', ['uri', 'uri-id', 'from-url'], ['parent-uri' => $mail['parent-uri'], 'reply' => false]);
866 // Making the post more compatible for Mastodon by:
867 // - Making it a note and not an article (no title)
868 // - Moving the title into the "summary" field that is used as a "content warning"
871 $mail['body'] = '[abstract]' . $mail['title'] . "[/abstract]\n" . $mail['body'];
875 $mail['author-link'] = $mail['owner-link'] = $mail['from-url'];
876 $mail['owner-id'] = $mail['author-id'];
877 $mail['allow_cid'] = '<'.$mail['contact-id'].'>';
878 $mail['allow_gid'] = '';
879 $mail['deny_cid'] = '';
880 $mail['deny_gid'] = '';
881 $mail['private'] = Item::PRIVATE;
882 $mail['deleted'] = false;
883 $mail['edited'] = $mail['created'];
884 $mail['plink'] = DI::baseUrl() . '/message/' . $mail['id'];
885 $mail['parent-uri'] = $reply['uri'];
886 $mail['parent-uri-id'] = $reply['uri-id'];
887 $mail['parent-author-id'] = Contact::getIdForURL($reply['from-url'], 0, false);
888 $mail['gravity'] = ($mail['reply'] ? GRAVITY_COMMENT: GRAVITY_PARENT);
889 $mail['event-type'] = '';
890 $mail['language'] = '';
897 * Creates an activity array for a given mail id
899 * @param integer $mail_id
900 * @param boolean $object_mode Is the activity item is used inside another object?
902 * @return array of activity
905 public static function createActivityFromMail($mail_id, $object_mode = false)
907 $mail = self::ItemArrayFromMail($mail_id);
911 $object = self::createNote($mail);
914 $data = ['@context' => ActivityPub::CONTEXT];
919 $data['id'] = $mail['uri'] . '/Create';
920 $data['type'] = 'Create';
921 $data['actor'] = $mail['author-link'];
922 $data['published'] = DateTimeFormat::utc($mail['created'] . '+00:00', DateTimeFormat::ATOM);
923 $data['instrument'] = self::getService();
924 $data = array_merge($data, self::createPermissionBlockForItem($mail, true));
926 if (empty($data['to']) && !empty($data['cc'])) {
927 $data['to'] = $data['cc'];
930 if (empty($data['to']) && !empty($data['bcc'])) {
931 $data['to'] = $data['bcc'];
937 $object['to'] = $data['to'];
938 $object['tag'] = [['type' => 'Mention', 'href' => $object['to'][0], 'name' => '']];
940 unset($object['cc']);
941 unset($object['bcc']);
943 $data['directMessage'] = true;
945 $data['object'] = $object;
947 $owner = User::getOwnerDataById($mail['uid']);
949 if (!$object_mode && !empty($owner)) {
950 return LDSignature::sign($data, $owner);
957 * Returns the activity type of a given item
961 * @return string with activity type
962 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
963 * @throws \ImagickException
965 private static function getTypeOfItem($item)
969 // Only check for a reshare, if it is a real reshare and no quoted reshare
970 if (strpos($item['body'], "[share") === 0) {
971 $announce = self::getAnnounceArray($item);
972 $reshared = !empty($announce);
977 } elseif ($item['verb'] == Activity::POST) {
978 if ($item['created'] == $item['edited']) {
983 } elseif ($item['verb'] == Activity::LIKE) {
985 } elseif ($item['verb'] == Activity::DISLIKE) {
987 } elseif ($item['verb'] == Activity::ATTEND) {
989 } elseif ($item['verb'] == Activity::ATTENDNO) {
991 } elseif ($item['verb'] == Activity::ATTENDMAYBE) {
992 $type = 'TentativeAccept';
993 } elseif ($item['verb'] == Activity::FOLLOW) {
995 } elseif ($item['verb'] == Activity::TAG) {
997 } elseif ($item['verb'] == Activity::ANNOUNCE) {
1007 * Creates the activity or fetches it from the cache
1009 * @param integer $item_id
1010 * @param boolean $force Force new cache entry
1012 * @return array with the activity
1013 * @throws \Exception
1015 public static function createCachedActivityFromItem($item_id, $force = false)
1017 $cachekey = 'APDelivery:createActivity:' . $item_id;
1020 $data = DI::cache()->get($cachekey);
1021 if (!is_null($data)) {
1026 $data = self::createActivityFromItem($item_id);
1028 DI::cache()->set($cachekey, $data, Duration::QUARTER_HOUR);
1033 * Creates an activity array for a given item id
1035 * @param integer $item_id
1036 * @param boolean $object_mode Is the activity item is used inside another object?
1038 * @return false|array
1039 * @throws \Exception
1041 public static function createActivityFromItem(int $item_id, bool $object_mode = false)
1043 Logger::info('Fetching activity', ['item' => $item_id]);
1044 $item = Post::selectFirst(Item::DELIVER_FIELDLIST, ['id' => $item_id, 'parent-network' => Protocol::NATIVE_SUPPORT]);
1045 if (!DBA::isResult($item)) {
1049 // In case of a forum post ensure to return the original post if author and forum are on the same machine
1050 if (($item['gravity'] == GRAVITY_PARENT) && !empty($item['forum_mode'])) {
1051 $author = Contact::getById($item['author-id'], ['nurl']);
1052 if (!empty($author['nurl'])) {
1053 $self = Contact::selectFirst(['uid'], ['nurl' => $author['nurl'], 'self' => true]);
1054 if (!empty($self['uid'])) {
1055 $forum_item = Post::selectFirst(Item::DELIVER_FIELDLIST, ['uri-id' => $item['uri-id'], 'uid' => $self['uid']]);
1056 if (DBA::isResult($forum_item)) {
1057 $item = $forum_item;
1063 if (empty($item['uri-id'])) {
1064 Logger::warning('Item without uri-id', ['item' => $item]);
1068 if (!$item['deleted']) {
1069 $condition = ['item-uri' => $item['uri'], 'protocol' => Conversation::PARCEL_ACTIVITYPUB];
1070 $conversation = DBA::selectFirst('conversation', ['source'], $condition);
1071 if (!$item['origin'] && DBA::isResult($conversation)) {
1072 $data = json_decode($conversation['source'], true);
1073 if (!empty($data['type'])) {
1074 if (in_array($data['type'], ['Create', 'Update'])) {
1076 unset($data['@context']);
1077 unset($data['signature']);
1079 Logger::info('Return stored conversation', ['item' => $item_id]);
1081 } elseif (in_array('as:' . $data['type'], Receiver::CONTENT_TYPES)) {
1082 if (!empty($data['@context'])) {
1083 $context = $data['@context'];
1084 unset($data['@context']);
1086 unset($data['actor']);
1093 $type = self::getTypeOfItem($item);
1095 if (!$object_mode) {
1096 $data = ['@context' => $context ?? ActivityPub::CONTEXT];
1098 if ($item['deleted'] && ($item['gravity'] == GRAVITY_ACTIVITY)) {
1100 } elseif ($item['deleted']) {
1107 if ($type == 'Delete') {
1108 $data['id'] = Item::newURI($item['uid'], $item['guid']) . '/' . $type;;
1109 } elseif (($item['gravity'] == GRAVITY_ACTIVITY) && ($type != 'Undo')) {
1110 $data['id'] = $item['uri'];
1112 $data['id'] = $item['uri'] . '/' . $type;
1115 $data['type'] = $type;
1117 if (($type != 'Announce') || ($item['gravity'] != GRAVITY_PARENT)) {
1118 $data['actor'] = $item['author-link'];
1120 $data['actor'] = $item['owner-link'];
1123 $data['published'] = DateTimeFormat::utc($item['created'] . '+00:00', DateTimeFormat::ATOM);
1125 $data['instrument'] = self::getService();
1127 $data = array_merge($data, self::createPermissionBlockForItem($item, false));
1129 if (in_array($data['type'], ['Create', 'Update', 'Delete'])) {
1130 $data['object'] = $object ?? self::createNote($item);
1131 } elseif ($data['type'] == 'Add') {
1132 $data = self::createAddTag($item, $data);
1133 } elseif ($data['type'] == 'Announce') {
1134 if ($item['verb'] == ACTIVITY::ANNOUNCE) {
1135 $data['object'] = $item['thr-parent'];
1137 $data = self::createAnnounce($item, $data);
1139 } elseif ($data['type'] == 'Follow') {
1140 $data['object'] = $item['parent-uri'];
1141 } elseif ($data['type'] == 'Undo') {
1142 $data['object'] = self::createActivityFromItem($item_id, true);
1144 $data['diaspora:guid'] = $item['guid'];
1145 if (!empty($item['signed_text'])) {
1146 $data['diaspora:like'] = $item['signed_text'];
1148 $data['object'] = $item['thr-parent'];
1151 if (!empty($item['contact-uid'])) {
1152 $uid = $item['contact-uid'];
1154 $uid = $item['uid'];
1157 $owner = User::getOwnerDataById($uid);
1159 Logger::info('Fetched activity', ['item' => $item_id, 'uid' => $uid]);
1161 // We don't sign if we aren't the actor. This is important for relaying content especially for forums
1162 if (!$object_mode && !empty($owner) && ($data['actor'] == $owner['url'])) {
1163 return LDSignature::sign($data, $owner);
1168 /// @todo Create "conversation" entry
1172 * Creates a location entry for a given item array
1174 * @param array $item
1176 * @return array with location array
1178 private static function createLocation($item)
1180 $location = ['type' => 'Place'];
1182 if (!empty($item['location'])) {
1183 $location['name'] = $item['location'];
1188 if (empty($item['coord'])) {
1189 $coord = Map::getCoordinates($item['location']);
1191 $coords = explode(' ', $item['coord']);
1192 if (count($coords) == 2) {
1193 $coord = ['lat' => $coords[0], 'lon' => $coords[1]];
1197 if (!empty($coord['lat']) && !empty($coord['lon'])) {
1198 $location['latitude'] = $coord['lat'];
1199 $location['longitude'] = $coord['lon'];
1206 * Returns a tag array for a given item array
1208 * @param array $item
1210 * @return array of tags
1211 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1213 private static function createTagList($item)
1217 $terms = Tag::getByURIId($item['uri-id'], [Tag::HASHTAG, Tag::MENTION, Tag::IMPLICIT_MENTION, Tag::EXCLUSIVE_MENTION]);
1218 foreach ($terms as $term) {
1219 if ($term['type'] == Tag::HASHTAG) {
1220 $url = DI::baseUrl() . '/search?tag=' . urlencode($term['name']);
1221 $tags[] = ['type' => 'Hashtag', 'href' => $url, 'name' => '#' . $term['name']];
1223 $contact = Contact::getByURL($term['url'], false, ['addr']);
1224 if (empty($contact)) {
1227 if (!empty($contact['addr'])) {
1228 $mention = '@' . $contact['addr'];
1230 $mention = '@' . $term['url'];
1233 $tags[] = ['type' => 'Mention', 'href' => $term['url'], 'name' => $mention];
1237 $announce = self::getAnnounceArray($item);
1238 // Mention the original author upon commented reshares
1239 if (!empty($announce['comment'])) {
1240 $tags[] = ['type' => 'Mention', 'href' => $announce['actor']['url'], 'name' => '@' . $announce['actor']['addr']];
1247 * Adds attachment data to the JSON document
1249 * @param array $item Data of the item that is to be posted
1250 * @param string $type Object type
1252 * @return array with attachment data
1253 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1255 private static function createAttachmentList($item, $type)
1259 $uriids = [$item['uri-id']];
1260 $shared = BBCode::fetchShareAttributes($item['body']);
1261 if (!empty($shared['guid'])) {
1262 $shared_item = Post::selectFirst(['uri-id'], ['guid' => $shared['guid']]);
1263 if (!empty($shared_item['uri-id'])) {
1264 $uriids[] = $shared_item['uri-id'];
1269 foreach ($uriids as $uriid) {
1270 foreach (Post\Media::getByURIId($uriid, [Post\Media::DOCUMENT, Post\Media::TORRENT]) as $attachment) {
1271 if (in_array($attachment['url'], $urls)) {
1274 $urls[] = $attachment['url'];
1276 $attach = ['type' => 'Document',
1277 'mediaType' => $attachment['mimetype'],
1278 'url' => $attachment['url'],
1279 'name' => $attachment['description']];
1281 if (!empty($attachment['height'])) {
1282 $attach['height'] = $attachment['height'];
1285 if (!empty($attachment['width'])) {
1286 $attach['width'] = $attachment['width'];
1289 if (!empty($attachment['preview'])) {
1290 $attach['image'] = $attachment['preview'];
1293 $attachments[] = $attach;
1297 if ($type != 'Note') {
1298 return $attachments;
1301 foreach ($uriids as $uriid) {
1302 foreach (Post\Media::getByURIId($uriid, [Post\Media::AUDIO, Post\Media::IMAGE, Post\Media::VIDEO]) as $attachment) {
1303 if (in_array($attachment['url'], $urls)) {
1306 $urls[] = $attachment['url'];
1308 $attach = ['type' => 'Document',
1309 'mediaType' => $attachment['mimetype'],
1310 'url' => $attachment['url'],
1311 'name' => $attachment['description']];
1313 if (!empty($attachment['height'])) {
1314 $attach['height'] = $attachment['height'];
1317 if (!empty($attachment['width'])) {
1318 $attach['width'] = $attachment['width'];
1321 if (!empty($attachment['preview'])) {
1322 $attach['image'] = $attachment['preview'];
1325 $attachments[] = $attach;
1327 // Currently deactivated, since it creates side effects on Mastodon and Pleroma.
1328 // It will be activated, once this cleared.
1330 foreach (Post\Media::getByURIId($uriid, [Post\Media::HTML]) as $attachment) {
1331 if (in_array($attachment['url'], $urls)) {
1334 $urls[] = $attachment['url'];
1336 $attachments[] = ['type' => 'Page',
1337 'mediaType' => $attachment['mimetype'],
1338 'url' => $attachment['url'],
1339 'name' => $attachment['description']];
1343 return $attachments;
1347 * Callback function to replace a Friendica style mention in a mention that is used on AP
1349 * @param array $match Matching values for the callback
1350 * @return string Replaced mention
1351 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1353 private static function mentionCallback($match)
1355 if (empty($match[1])) {
1359 $data = Contact::getByURL($match[1], false, ['url', 'alias', 'nick']);
1360 if (empty($data['nick'])) {
1364 return '[url=' . $data['url'] . ']@' . $data['nick'] . '[/url]';
1368 * Callback function to replace a Friendica style mention in a mention for a summary
1370 * @param array $match Matching values for the callback
1371 * @return string Replaced mention
1372 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1374 private static function mentionAddrCallback($match)
1376 if (empty($match[1])) {
1380 $data = Contact::getByURL($match[1], false, ['addr']);
1381 if (empty($data['addr'])) {
1385 return '@' . $data['addr'];
1389 * Remove image elements since they are added as attachment
1391 * @param string $body
1393 * @return string with removed images
1395 private static function removePictures($body)
1397 // Simplify image codes
1398 $body = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '[img]$3[/img]', $body);
1399 $body = preg_replace("/\[img\=(.*?)\](.*?)\[\/img\]/ism", '[img]$1[/img]', $body);
1401 // Now remove local links
1402 $body = preg_replace_callback(
1403 '/\[url=([^\[\]]*)\]\[img\](.*)\[\/img\]\[\/url\]/Usi',
1405 // We remove the link when it is a link to a local photo page
1406 if (Photo::isLocalPage($match[1])) {
1409 // otherwise we just return the link
1410 return '[url]' . $match[1] . '[/url]';
1415 // Remove all pictures
1416 $body = preg_replace("/\[img\]([^\[\]]*)\[\/img\]/Usi", '', $body);
1422 * Fetches the "context" value for a givem item array from the "conversation" table
1424 * @param array $item
1426 * @return string with context url
1427 * @throws \Exception
1429 private static function fetchContextURLForItem($item)
1431 $conversation = DBA::selectFirst('conversation', ['conversation-href', 'conversation-uri'], ['item-uri' => $item['parent-uri']]);
1432 if (DBA::isResult($conversation) && !empty($conversation['conversation-href'])) {
1433 $context_uri = $conversation['conversation-href'];
1434 } elseif (DBA::isResult($conversation) && !empty($conversation['conversation-uri'])) {
1435 $context_uri = $conversation['conversation-uri'];
1437 $context_uri = $item['parent-uri'] . '#context';
1439 return $context_uri;
1443 * Returns if the post contains sensitive content ("nsfw")
1445 * @param integer $uri_id
1448 * @throws \Exception
1450 private static function isSensitive($uri_id)
1452 return DBA::exists('tag-view', ['uri-id' => $uri_id, 'name' => 'nsfw']);
1456 * Creates event data
1458 * @param array $item
1460 * @return array with the event data
1461 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1463 private static function createEvent($item)
1466 $event['name'] = $item['event-summary'];
1467 $event['content'] = BBCode::convertForUriId($item['uri-id'], $item['event-desc'], BBCode::ACTIVITYPUB);
1468 $event['startTime'] = DateTimeFormat::utc($item['event-start'] . '+00:00', DateTimeFormat::ATOM);
1470 if (!$item['event-nofinish']) {
1471 $event['endTime'] = DateTimeFormat::utc($item['event-finish'] . '+00:00', DateTimeFormat::ATOM);
1474 if (!empty($item['event-location'])) {
1475 $item['location'] = $item['event-location'];
1476 $event['location'] = self::createLocation($item);
1479 $event['dfrn:adjust'] = (bool)$item['event-adjust'];
1485 * Creates a note/article object array
1487 * @param array $item
1489 * @return array with the object data
1490 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1491 * @throws \ImagickException
1493 public static function createNote($item)
1499 if ($item['event-type'] == 'event') {
1501 } elseif (!empty($item['title'])) {
1507 if ($item['deleted']) {
1508 $type = 'Tombstone';
1512 $data['id'] = $item['uri'];
1513 $data['type'] = $type;
1515 if ($item['deleted']) {
1519 $data['summary'] = BBCode::toPlaintext(BBCode::getAbstract($item['body'], Protocol::ACTIVITYPUB));
1521 if ($item['uri'] != $item['thr-parent']) {
1522 $data['inReplyTo'] = $item['thr-parent'];
1524 $data['inReplyTo'] = null;
1527 $data['diaspora:guid'] = $item['guid'];
1528 $data['published'] = DateTimeFormat::utc($item['created'] . '+00:00', DateTimeFormat::ATOM);
1530 if ($item['created'] != $item['edited']) {
1531 $data['updated'] = DateTimeFormat::utc($item['edited'] . '+00:00', DateTimeFormat::ATOM);
1534 $data['url'] = $item['plink'];
1535 $data['attributedTo'] = $item['author-link'];
1536 $data['sensitive'] = self::isSensitive($item['uri-id']);
1537 $data['context'] = self::fetchContextURLForItem($item);
1539 if (!empty($item['title'])) {
1540 $data['name'] = BBCode::toPlaintext($item['title'], false);
1543 $permission_block = self::createPermissionBlockForItem($item, false);
1545 $body = $item['body'];
1547 if ($type == 'Note') {
1548 $body = $item['raw-body'] ?? self::removePictures($body);
1552 * @todo Improve the automated summary
1553 * This part is currently deactivated. The automated summary seems to be more
1554 * confusing than helping. But possibly we will find a better way.
1555 * So the code is left here for now as a reminder
1557 * } elseif (($type == 'Article') && empty($data['summary'])) {
1558 * $regexp = "/[@!]\[url\=([^\[\]]*)\].*?\[\/url\]/ism";
1559 * $summary = preg_replace_callback($regexp, ['self', 'mentionAddrCallback'], $body);
1560 * $data['summary'] = BBCode::toPlaintext(Plaintext::shorten(self::removePictures($summary), 1000));
1564 if (empty($item['uid']) || !Feature::isEnabled($item['uid'], 'explicit_mentions')) {
1565 $body = self::prependMentions($body, $item['uri-id'], $item['author-link']);
1568 if ($type == 'Event') {
1569 $data = array_merge($data, self::createEvent($item));
1571 $regexp = "/[@!]\[url\=([^\[\]]*)\].*?\[\/url\]/ism";
1572 $body = preg_replace_callback($regexp, ['self', 'mentionCallback'], $body);
1574 $data['content'] = BBCode::convertForUriId($item['uri-id'], $body, BBCode::ACTIVITYPUB);
1577 // The regular "content" field does contain a minimized HTML. This is done since systems like
1578 // Mastodon has got problems with - for example - embedded pictures.
1579 // The contentMap does contain the unmodified HTML.
1580 $language = self::getLanguage($item);
1581 if (!empty($language)) {
1582 $regexp = "/[@!]\[url\=([^\[\]]*)\].*?\[\/url\]/ism";
1583 $richbody = preg_replace_callback($regexp, ['self', 'mentionCallback'], $item['body']);
1584 $richbody = BBCode::removeAttachment($richbody);
1586 $data['contentMap'][$language] = BBCode::convertForUriId($item['uri-id'], $richbody, BBCode::EXTERNAL);
1589 $data['source'] = ['content' => $item['body'], 'mediaType' => "text/bbcode"];
1591 if (!empty($item['signed_text']) && ($item['uri'] != $item['thr-parent'])) {
1592 $data['diaspora:comment'] = $item['signed_text'];
1595 $data['attachment'] = self::createAttachmentList($item, $type);
1596 $data['tag'] = self::createTagList($item);
1598 if (empty($data['location']) && (!empty($item['coord']) || !empty($item['location']))) {
1599 $data['location'] = self::createLocation($item);
1602 if (!empty($item['app'])) {
1603 $data['generator'] = ['type' => 'Application', 'name' => $item['app']];
1606 $data = array_merge($data, $permission_block);
1612 * Fetches the language from the post, the user or the system.
1614 * @param array $item
1616 * @return string language string
1618 private static function getLanguage(array $item)
1620 // Try to fetch the language from the post itself
1621 if (!empty($item['language'])) {
1622 $languages = array_keys(json_decode($item['language'], true));
1623 if (!empty($languages[0])) {
1624 return $languages[0];
1628 // Otherwise use the user's language
1629 if (!empty($item['uid'])) {
1630 $user = DBA::selectFirst('user', ['language'], ['uid' => $item['uid']]);
1631 if (!empty($user['language'])) {
1632 return $user['language'];
1636 // And finally just use the system language
1637 return DI::config()->get('system', 'language');
1641 * Creates an an "add tag" entry
1643 * @param array $item
1644 * @param array $data activity data
1646 * @return array with activity data for adding tags
1647 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1648 * @throws \ImagickException
1650 private static function createAddTag($item, $data)
1652 $object = XML::parseString($item['object']);
1653 $target = XML::parseString($item["target"]);
1655 $data['diaspora:guid'] = $item['guid'];
1656 $data['actor'] = $item['author-link'];
1657 $data['target'] = (string)$target->id;
1658 $data['summary'] = BBCode::toPlaintext($item['body']);
1659 $data['object'] = ['id' => (string)$object->id, 'type' => 'tag', 'name' => (string)$object->title, 'content' => (string)$object->content];
1665 * Creates an announce object entry
1667 * @param array $item
1668 * @param array $data activity data
1670 * @return array with activity data
1671 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1672 * @throws \ImagickException
1674 private static function createAnnounce($item, $data)
1676 $orig_body = $item['body'];
1677 $announce = self::getAnnounceArray($item);
1678 if (empty($announce)) {
1679 $data['type'] = 'Create';
1680 $data['object'] = self::createNote($item);
1684 if (empty($announce['comment'])) {
1685 // Pure announce, without a quote
1686 $data['type'] = 'Announce';
1687 $data['object'] = $announce['object']['uri'];
1692 $data['type'] = 'Create';
1693 $item['body'] = $announce['comment'] . "\n" . $announce['object']['plink'];
1694 $data['object'] = self::createNote($item);
1696 /// @todo Finally descide how to implement this in AP. This is a possible way:
1697 $data['object']['attachment'][] = self::createNote($announce['object']);
1699 $data['object']['source']['content'] = $orig_body;
1704 * Return announce related data if the item is an annunce
1706 * @param array $item
1710 public static function getAnnounceArray($item)
1712 $reshared = Item::getShareArray($item);
1713 if (empty($reshared['guid'])) {
1717 $reshared_item = Post::selectFirst(Item::DELIVER_FIELDLIST, ['guid' => $reshared['guid']]);
1718 if (!DBA::isResult($reshared_item)) {
1722 if (!in_array($reshared_item['network'], [Protocol::ACTIVITYPUB, Protocol::DFRN])) {
1726 $profile = APContact::getByURL($reshared_item['author-link'], false);
1727 if (empty($profile)) {
1731 return ['object' => $reshared_item, 'actor' => $profile, 'comment' => $reshared['comment']];
1735 * Checks if the provided item array is an announce
1737 * @param array $item
1741 public static function isAnnounce($item)
1743 if (!empty($item['verb']) && ($item['verb'] == Activity::ANNOUNCE)) {
1747 $announce = self::getAnnounceArray($item);
1748 if (empty($announce)) {
1752 return empty($announce['comment']);
1756 * Creates an activity id for a given contact id
1758 * @param integer $cid Contact ID of target
1760 * @return bool|string activity id
1762 public static function activityIDFromContact($cid)
1764 $contact = DBA::selectFirst('contact', ['uid', 'id', 'created'], ['id' => $cid]);
1765 if (!DBA::isResult($contact)) {
1769 $hash = hash('ripemd128', $contact['uid'].'-'.$contact['id'].'-'.$contact['created']);
1770 $uuid = substr($hash, 0, 8). '-' . substr($hash, 8, 4) . '-' . substr($hash, 12, 4) . '-' . substr($hash, 16, 4) . '-' . substr($hash, 20, 12);
1771 return DI::baseUrl() . '/activity/' . $uuid;
1775 * Transmits a contact suggestion to a given inbox
1777 * @param integer $uid User ID
1778 * @param string $inbox Target inbox
1779 * @param integer $suggestion_id Suggestion ID
1781 * @return boolean was the transmission successful?
1782 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1784 public static function sendContactSuggestion($uid, $inbox, $suggestion_id)
1786 $owner = User::getOwnerDataById($uid);
1788 $suggestion = DI::fsuggest()->getById($suggestion_id);
1790 $data = ['@context' => ActivityPub::CONTEXT,
1791 'id' => DI::baseUrl() . '/activity/' . System::createGUID(),
1792 'type' => 'Announce',
1793 'actor' => $owner['url'],
1794 'object' => $suggestion->url,
1795 'content' => $suggestion->note,
1796 'instrument' => self::getService(),
1797 'to' => [ActivityPub::PUBLIC_COLLECTION],
1800 $signed = LDSignature::sign($data, $owner);
1802 Logger::log('Deliver profile deletion for user ' . $uid . ' to ' . $inbox . ' via ActivityPub', Logger::DEBUG);
1803 return HTTPSignature::transmit($signed, $inbox, $uid);
1807 * Transmits a profile relocation to a given inbox
1809 * @param integer $uid User ID
1810 * @param string $inbox Target inbox
1812 * @return boolean was the transmission successful?
1813 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1815 public static function sendProfileRelocation($uid, $inbox)
1817 $owner = User::getOwnerDataById($uid);
1819 $data = ['@context' => ActivityPub::CONTEXT,
1820 'id' => DI::baseUrl() . '/activity/' . System::createGUID(),
1821 'type' => 'dfrn:relocate',
1822 'actor' => $owner['url'],
1823 'object' => $owner['url'],
1824 'published' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
1825 'instrument' => self::getService(),
1826 'to' => [ActivityPub::PUBLIC_COLLECTION],
1829 $signed = LDSignature::sign($data, $owner);
1831 Logger::log('Deliver profile relocation for user ' . $uid . ' to ' . $inbox . ' via ActivityPub', Logger::DEBUG);
1832 return HTTPSignature::transmit($signed, $inbox, $uid);
1836 * Transmits a profile deletion to a given inbox
1838 * @param integer $uid User ID
1839 * @param string $inbox Target inbox
1841 * @return boolean was the transmission successful?
1842 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1844 public static function sendProfileDeletion($uid, $inbox)
1846 $owner = User::getOwnerDataById($uid);
1848 if (empty($owner)) {
1849 Logger::error('No owner data found, the deletion message cannot be processed.', ['user' => $uid]);
1853 if (empty($owner['uprvkey'])) {
1854 Logger::error('No private key for owner found, the deletion message cannot be processed.', ['user' => $uid]);
1858 $data = ['@context' => ActivityPub::CONTEXT,
1859 'id' => DI::baseUrl() . '/activity/' . System::createGUID(),
1861 'actor' => $owner['url'],
1862 'object' => $owner['url'],
1863 'published' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
1864 'instrument' => self::getService(),
1865 'to' => [ActivityPub::PUBLIC_COLLECTION],
1868 $signed = LDSignature::sign($data, $owner);
1870 Logger::log('Deliver profile deletion for user ' . $uid . ' to ' . $inbox . ' via ActivityPub', Logger::DEBUG);
1871 return HTTPSignature::transmit($signed, $inbox, $uid);
1875 * Transmits a profile change to a given inbox
1877 * @param integer $uid User ID
1878 * @param string $inbox Target inbox
1880 * @return boolean was the transmission successful?
1881 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1882 * @throws \ImagickException
1884 public static function sendProfileUpdate($uid, $inbox)
1886 $owner = User::getOwnerDataById($uid);
1887 $profile = APContact::getByURL($owner['url']);
1889 $data = ['@context' => ActivityPub::CONTEXT,
1890 'id' => DI::baseUrl() . '/activity/' . System::createGUID(),
1892 'actor' => $owner['url'],
1893 'object' => self::getProfile($uid),
1894 'published' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
1895 'instrument' => self::getService(),
1896 'to' => [$profile['followers']],
1899 $signed = LDSignature::sign($data, $owner);
1901 Logger::log('Deliver profile update for user ' . $uid . ' to ' . $inbox . ' via ActivityPub', Logger::DEBUG);
1902 return HTTPSignature::transmit($signed, $inbox, $uid);
1906 * Transmits a given activity to a target
1908 * @param string $activity Type name
1909 * @param string $target Target profile
1910 * @param integer $uid User ID
1912 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1913 * @throws \ImagickException
1914 * @throws \Exception
1916 public static function sendActivity($activity, $target, $uid, $id = '')
1918 $profile = APContact::getByURL($target);
1919 if (empty($profile['inbox'])) {
1920 Logger::warning('No inbox found for target', ['target' => $target, 'profile' => $profile]);
1924 $owner = User::getOwnerDataById($uid);
1927 $id = DI::baseUrl() . '/activity/' . System::createGUID();
1930 $data = ['@context' => ActivityPub::CONTEXT,
1932 'type' => $activity,
1933 'actor' => $owner['url'],
1934 'object' => $profile['url'],
1935 'instrument' => self::getService(),
1936 'to' => [$profile['url']]];
1938 Logger::log('Sending activity ' . $activity . ' to ' . $target . ' for user ' . $uid, Logger::DEBUG);
1940 $signed = LDSignature::sign($data, $owner);
1941 return HTTPSignature::transmit($signed, $profile['inbox'], $uid);
1945 * Transmits a "follow object" activity to a target
1946 * This is a preparation for sending automated "follow" requests when receiving "Announce" messages
1948 * @param string $object Object URL
1949 * @param string $target Target profile
1950 * @param integer $uid User ID
1952 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1953 * @throws \ImagickException
1954 * @throws \Exception
1956 public static function sendFollowObject($object, $target, $uid = 0)
1958 $profile = APContact::getByURL($target);
1959 if (empty($profile['inbox'])) {
1960 Logger::warning('No inbox found for target', ['target' => $target, 'profile' => $profile]);
1965 // Fetch the list of administrators
1966 $admin_mail = explode(',', str_replace(' ', '', DI::config()->get('config', 'admin_email')));
1968 // We need to use some user as a sender. It doesn't care who it will send. We will use an administrator account.
1969 $condition = ['verified' => true, 'blocked' => false, 'account_removed' => false, 'account_expired' => false, 'email' => $admin_mail];
1970 $first_user = DBA::selectFirst('user', ['uid'], $condition);
1971 $uid = $first_user['uid'];
1974 $condition = ['verb' => Activity::FOLLOW, 'uid' => 0, 'parent-uri' => $object,
1975 'author-id' => Contact::getPublicIdByUserId($uid)];
1976 if (Post::exists($condition)) {
1977 Logger::log('Follow for ' . $object . ' for user ' . $uid . ' does already exist.', Logger::DEBUG);
1981 $owner = User::getOwnerDataById($uid);
1983 $data = ['@context' => ActivityPub::CONTEXT,
1984 'id' => DI::baseUrl() . '/activity/' . System::createGUID(),
1986 'actor' => $owner['url'],
1987 'object' => $object,
1988 'instrument' => self::getService(),
1989 'to' => [$profile['url']]];
1991 Logger::log('Sending follow ' . $object . ' to ' . $target . ' for user ' . $uid, Logger::DEBUG);
1993 $signed = LDSignature::sign($data, $owner);
1994 return HTTPSignature::transmit($signed, $profile['inbox'], $uid);
1998 * Transmit a message that the contact request had been accepted
2000 * @param string $target Target profile
2002 * @param integer $uid User ID
2003 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2004 * @throws \ImagickException
2006 public static function sendContactAccept($target, $id, $uid)
2008 $profile = APContact::getByURL($target);
2009 if (empty($profile['inbox'])) {
2010 Logger::warning('No inbox found for target', ['target' => $target, 'profile' => $profile]);
2014 $owner = User::getOwnerDataById($uid);
2015 $data = ['@context' => ActivityPub::CONTEXT,
2016 'id' => DI::baseUrl() . '/activity/' . System::createGUID(),
2018 'actor' => $owner['url'],
2020 'id' => (string)$id,
2022 'actor' => $profile['url'],
2023 'object' => $owner['url']
2025 'instrument' => self::getService(),
2026 'to' => [$profile['url']]];
2028 Logger::debug('Sending accept to ' . $target . ' for user ' . $uid . ' with id ' . $id);
2030 $signed = LDSignature::sign($data, $owner);
2031 HTTPSignature::transmit($signed, $profile['inbox'], $uid);
2035 * Reject a contact request or terminates the contact relation
2037 * @param string $target Target profile
2039 * @param integer $uid User ID
2040 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2041 * @throws \ImagickException
2043 public static function sendContactReject($target, $id, $uid)
2045 $profile = APContact::getByURL($target);
2046 if (empty($profile['inbox'])) {
2047 Logger::warning('No inbox found for target', ['target' => $target, 'profile' => $profile]);
2051 $owner = User::getOwnerDataById($uid);
2052 $data = ['@context' => ActivityPub::CONTEXT,
2053 'id' => DI::baseUrl() . '/activity/' . System::createGUID(),
2055 'actor' => $owner['url'],
2057 'id' => (string)$id,
2059 'actor' => $profile['url'],
2060 'object' => $owner['url']
2062 'instrument' => self::getService(),
2063 'to' => [$profile['url']]];
2065 Logger::debug('Sending reject to ' . $target . ' for user ' . $uid . ' with id ' . $id);
2067 $signed = LDSignature::sign($data, $owner);
2068 HTTPSignature::transmit($signed, $profile['inbox'], $uid);
2072 * Transmits a message that we don't want to follow this contact anymore
2074 * @param string $target Target profile
2075 * @param integer $uid User ID
2076 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2077 * @throws \ImagickException
2078 * @throws \Exception
2079 * @return bool success
2081 public static function sendContactUndo($target, $cid, $uid)
2083 $profile = APContact::getByURL($target);
2084 if (empty($profile['inbox'])) {
2085 Logger::warning('No inbox found for target', ['target' => $target, 'profile' => $profile]);
2089 $object_id = self::activityIDFromContact($cid);
2090 if (empty($object_id)) {
2094 $id = DI::baseUrl() . '/activity/' . System::createGUID();
2096 $owner = User::getOwnerDataById($uid);
2097 $data = ['@context' => ActivityPub::CONTEXT,
2100 'actor' => $owner['url'],
2101 'object' => ['id' => $object_id, 'type' => 'Follow',
2102 'actor' => $owner['url'],
2103 'object' => $profile['url']],
2104 'instrument' => self::getService(),
2105 'to' => [$profile['url']]];
2107 Logger::log('Sending undo to ' . $target . ' for user ' . $uid . ' with id ' . $id, Logger::DEBUG);
2109 $signed = LDSignature::sign($data, $owner);
2110 return HTTPSignature::transmit($signed, $profile['inbox'], $uid);
2113 private static function prependMentions($body, int $uriid, string $authorLink)
2117 foreach (Tag::getByURIId($uriid, [Tag::IMPLICIT_MENTION]) as $tag) {
2118 $profile = Contact::getByURL($tag['url'], false, ['addr', 'contact-type', 'nick']);
2119 if (!empty($profile['addr'])
2120 && $profile['contact-type'] != Contact::TYPE_COMMUNITY
2121 && !strstr($body, $profile['addr'])
2122 && !strstr($body, $tag['url'])
2123 && $tag['url'] !== $authorLink
2125 $mentions[] = '@[url=' . $tag['url'] . ']' . $profile['nick'] . '[/url]';
2129 $mentions[] = $body;
2131 return implode(' ', $mentions);