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', 'net-publish'];
329 $profile = DBA::selectFirst('profile', $fields, ['uid' => $uid]);
330 if (!DBA::isResult($profile)) {
334 $fields = ['id', 'name', 'url', 'location', 'about', 'avatar', 'photo', 'updated'];
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' => '', 'net-publish' => false];
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['discoverable'] = $profile['net-publish'];
379 $data['publicKey'] = ['id' => $contact['url'] . '#main-key',
380 'owner' => $contact['url'],
381 'publicKeyPem' => $user['pubkey']];
382 $data['endpoints'] = ['sharedInbox' => DI::baseUrl() . '/inbox'];
383 $data['icon'] = ['type' => 'Image', 'url' => Contact::getAvatarUrlForId($contact['id'], '', $contact['updated'])];
385 $resourceid = Photo::ridFromURI($contact['photo']);
386 if (!empty($resourceid)) {
387 $photo = Photo::selectFirst(['type'], ["resource-id" => $resourceid]);
388 if (!empty($photo['type'])) {
389 $data['icon']['mediaType'] = $photo['type'];
393 if (!empty($contact['header'])) {
394 $data['image'] = ['type' => 'Image', 'url' => Contact::getHeaderUrlForId($contact['id'], '', $contact['updated'])];
396 $resourceid = Photo::ridFromURI($contact['header']);
397 if (!empty($resourceid)) {
398 $photo = Photo::selectFirst(['type'], ["resource-id" => $resourceid]);
399 if (!empty($photo['type'])) {
400 $data['image']['mediaType'] = $photo['type'];
405 $data['generator'] = self::getService();
407 // tags: https://kitty.town/@inmysocks/100656097926961126.json
412 * @param string $username
414 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
416 public static function getDeletedUser($username)
419 '@context' => ActivityPub::CONTEXT,
420 'id' => DI::baseUrl() . '/profile/' . $username,
421 'type' => 'Tombstone',
422 'published' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
423 'updated' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
424 'deleted' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
429 * Returns an array with permissions of a given item array
433 * @return array with permissions
434 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
435 * @throws \ImagickException
437 private static function fetchPermissionBlockFromConversation($item)
439 if (empty($item['thr-parent'])) {
443 $condition = ['item-uri' => $item['thr-parent'], 'protocol' => Conversation::PARCEL_ACTIVITYPUB];
444 $conversation = DBA::selectFirst('conversation', ['source'], $condition);
445 if (!DBA::isResult($conversation)) {
449 $activity = json_decode($conversation['source'], true);
451 $actor = JsonLD::fetchElement($activity, 'actor', 'id');
452 if (!empty($actor)) {
453 $permissions['to'][] = $actor;
454 $profile = APContact::getByURL($actor);
459 $item_profile = APContact::getByURL($item['author-link']);
460 $exclude[] = $item['author-link'];
462 if ($item['gravity'] == GRAVITY_PARENT) {
463 $exclude[] = $item['owner-link'];
466 foreach (['to', 'cc', 'bto', 'bcc'] as $element) {
467 if (empty($activity[$element])) {
470 if (is_string($activity[$element])) {
471 $activity[$element] = [$activity[$element]];
474 foreach ($activity[$element] as $receiver) {
475 if (empty($receiver)) {
479 if (!empty($profile['followers']) && $receiver == $profile['followers'] && !empty($item_profile['followers'])) {
480 $permissions[$element][] = $item_profile['followers'];
481 } elseif (!in_array($receiver, $exclude)) {
482 $permissions[$element][] = $receiver;
490 * Check if the given item id is from ActivityPub
492 * @param integer $item_id
493 * @return boolean "true" if the post is from ActivityPub
495 private static function isAPPost(int $item_id)
497 if (empty($item_id)) {
501 return Post::exists(['id' => $item_id, 'network' => Protocol::ACTIVITYPUB]);
505 * Creates an array of permissions from an item thread
507 * @param array $item Item array
508 * @param boolean $blindcopy addressing via "bcc" or "cc"?
509 * @param integer $last_id Last item id for adding receivers
510 * @param boolean $forum_mode "true" means that we are sending content to a forum
512 * @return array with permission data
513 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
514 * @throws \ImagickException
516 private static function createPermissionBlockForItem($item, $blindcopy, $last_id = 0, $forum_mode = false)
519 $last_id = $item['id'];
524 // Check if we should always deliver our stuff via BCC
525 if (!empty($item['uid'])) {
526 $profile = User::getOwnerDataById($item['uid']);
527 if (!empty($profile)) {
528 $always_bcc = $profile['hide-friends'];
532 if (DI::config()->get('system', 'ap_always_bcc')) {
536 if (self::isAnnounce($item) || DI::config()->get('debug', 'total_ap_delivery') || self::isAPPost($last_id)) {
537 // Will be activated in a later step
538 $networks = Protocol::FEDERATED;
540 // For now only send to these contacts:
541 $networks = [Protocol::ACTIVITYPUB, Protocol::OSTATUS];
544 $data = ['to' => [], 'cc' => [], 'bcc' => []];
546 if ($item['gravity'] == GRAVITY_PARENT) {
547 $actor_profile = APContact::getByURL($item['owner-link']);
549 $actor_profile = APContact::getByURL($item['author-link']);
554 $terms = Tag::getByURIId($item['uri-id'], [Tag::MENTION, Tag::IMPLICIT_MENTION, Tag::EXCLUSIVE_MENTION]);
556 if ($item['private'] != Item::PRIVATE) {
557 // Directly mention the original author upon a quoted reshare.
558 // Else just ensure that the original author receives the reshare.
559 $announce = self::getAnnounceArray($item);
560 if (!empty($announce['comment'])) {
561 $data['to'][] = $announce['actor']['url'];
562 } elseif (!empty($announce)) {
563 $data['cc'][] = $announce['actor']['url'];
566 $data = array_merge($data, self::fetchPermissionBlockFromConversation($item));
568 // Check if the item is completely public or unlisted
569 if ($item['private'] == Item::PUBLIC) {
570 $data['to'][] = ActivityPub::PUBLIC_COLLECTION;
572 $data['cc'][] = ActivityPub::PUBLIC_COLLECTION;
575 foreach ($terms as $term) {
576 $profile = APContact::getByURL($term['url'], false);
577 if (!empty($profile)) {
578 if ($term['type'] == Tag::EXCLUSIVE_MENTION) {
580 if (!empty($profile['followers']) && ($profile['type'] == 'Group')) {
581 $data['cc'][] = $profile['followers'];
584 $data['to'][] = $profile['url'];
588 $receiver_list = Item::enumeratePermissions($item, true);
590 foreach ($terms as $term) {
591 $cid = Contact::getIdForURL($term['url'], $item['uid']);
592 if (!empty($cid) && in_array($cid, $receiver_list)) {
593 $contact = DBA::selectFirst('contact', ['url', 'network', 'protocol', 'gsid'], ['id' => $cid, 'network' => Protocol::FEDERATED]);
594 if (!DBA::isResult($contact) || !self::isAPContact($contact, $networks)) {
598 if (!empty($profile = APContact::getByURL($contact['url'], false))) {
599 $data['to'][] = $profile['url'];
604 foreach ($receiver_list as $receiver) {
605 $contact = DBA::selectFirst('contact', ['url', 'hidden', 'network', 'protocol', 'gsid'], ['id' => $receiver, 'network' => Protocol::FEDERATED]);
606 if (!DBA::isResult($contact) || !self::isAPContact($contact, $networks)) {
610 if (!empty($profile = APContact::getByURL($contact['url'], false))) {
611 if ($contact['hidden'] || $always_bcc) {
612 $data['bcc'][] = $profile['url'];
614 $data['cc'][] = $profile['url'];
620 if (!empty($item['parent'])) {
621 $parents = Post::select(['id', 'author-link', 'owner-link', 'gravity', 'uri'], ['parent' => $item['parent']]);
622 while ($parent = Post::fetch($parents)) {
623 if ($parent['gravity'] == GRAVITY_PARENT) {
624 $profile = APContact::getByURL($parent['owner-link'], false);
625 if (!empty($profile)) {
626 if ($item['gravity'] != GRAVITY_PARENT) {
627 // Comments to forums are directed to the forum
628 // But comments to forums aren't directed to the followers collection
629 // This rule is only valid when the actor isn't the forum.
630 // The forum needs to transmit their content to their followers.
631 if (($profile['type'] == 'Group') && ($profile['url'] != ($actor_profile['url'] ?? ''))) {
632 $data['to'][] = $profile['url'];
634 $data['cc'][] = $profile['url'];
635 if (($item['private'] != Item::PRIVATE) && !empty($actor_profile['followers'])) {
636 $data['cc'][] = $actor_profile['followers'];
639 } elseif (!$exclusive) {
640 // Public thread parent post always are directed to the followers.
641 // This mustn't be done by posts that are directed to forum servers via the exclusive mention.
642 // But possibly in that case we could add the "followers" collection of the forum to the message.
643 if (($item['private'] != Item::PRIVATE) && !$forum_mode) {
644 $data['cc'][] = $actor_profile['followers'];
650 // Don't include data from future posts
651 if ($parent['id'] >= $last_id) {
655 $profile = APContact::getByURL($parent['author-link'], false);
656 if (!empty($profile)) {
657 if (($profile['type'] == 'Group') || ($parent['uri'] == $item['thr-parent'])) {
658 $data['to'][] = $profile['url'];
660 $data['cc'][] = $profile['url'];
664 DBA::close($parents);
667 $data['to'] = array_unique($data['to']);
668 $data['cc'] = array_unique($data['cc']);
669 $data['bcc'] = array_unique($data['bcc']);
671 if (($key = array_search($item['author-link'], $data['to'])) !== false) {
672 unset($data['to'][$key]);
675 if (($key = array_search($item['author-link'], $data['cc'])) !== false) {
676 unset($data['cc'][$key]);
679 if (($key = array_search($item['author-link'], $data['bcc'])) !== false) {
680 unset($data['bcc'][$key]);
683 foreach ($data['to'] as $to) {
684 if (($key = array_search($to, $data['cc'])) !== false) {
685 unset($data['cc'][$key]);
688 if (($key = array_search($to, $data['bcc'])) !== false) {
689 unset($data['bcc'][$key]);
693 foreach ($data['cc'] as $cc) {
694 if (($key = array_search($cc, $data['bcc'])) !== false) {
695 unset($data['bcc'][$key]);
699 $receivers = ['to' => array_values($data['to']), 'cc' => array_values($data['cc']), 'bcc' => array_values($data['bcc'])];
702 unset($receivers['bcc']);
709 * Check if an inbox is archived
711 * @param string $url Inbox url
713 * @return boolean "true" if inbox is archived
715 public static function archivedInbox($url)
717 return DBA::exists('inbox-status', ['url' => $url, 'archive' => true]);
721 * Check if a given contact should be delivered via AP
723 * @param array $contact
724 * @param array $networks
728 private static function isAPContact(array $contact, array $networks)
730 if (in_array($contact['network'], $networks) || ($contact['protocol'] == Protocol::ACTIVITYPUB)) {
734 return GServer::getProtocol($contact['gsid'] ?? 0) == Post\DeliveryData::ACTIVITYPUB;
738 * Fetches a list of inboxes of followers of a given user
740 * @param integer $uid User ID
741 * @param boolean $personal fetch personal inboxes
742 * @param boolean $all_ap Retrieve all AP enabled inboxes
744 * @return array of follower inboxes
745 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
746 * @throws \ImagickException
748 public static function fetchTargetInboxesforUser($uid, $personal = false, bool $all_ap = false)
754 if (!empty($item['uid'])) {
755 $profile = User::getOwnerDataById($item['uid']);
756 if (!empty($profile)) {
757 $isforum = $profile['account-type'] == User::ACCOUNT_TYPE_COMMUNITY;
761 if (DI::config()->get('debug', 'total_ap_delivery') || $all_ap) {
762 // Will be activated in a later step
763 $networks = Protocol::FEDERATED;
765 // For now only send to these contacts:
766 $networks = [Protocol::ACTIVITYPUB, Protocol::OSTATUS];
769 $condition = ['uid' => $uid, 'archive' => false, 'pending' => false, 'blocked' => false, 'network' => Protocol::FEDERATED];
772 $condition['rel'] = [Contact::FOLLOWER, Contact::FRIEND];
775 $contacts = DBA::select('contact', ['id', 'url', 'network', 'protocol', 'gsid'], $condition);
776 while ($contact = DBA::fetch($contacts)) {
777 if (!self::isAPContact($contact, $networks)) {
781 if ($isforum && ($contact['network'] == Protocol::DFRN)) {
785 if (Network::isUrlBlocked($contact['url'])) {
789 $profile = APContact::getByURL($contact['url'], false);
790 if (!empty($profile)) {
791 if (empty($profile['sharedinbox']) || $personal || Contact::isLocal($contact['url'])) {
792 $target = $profile['inbox'];
794 $target = $profile['sharedinbox'];
796 if (!self::archivedInbox($target)) {
797 $inboxes[$target][] = $contact['id'];
801 DBA::close($contacts);
807 * Fetches an array of inboxes for the given item and user
809 * @param array $item Item array
810 * @param integer $uid User ID
811 * @param boolean $personal fetch personal inboxes
812 * @param integer $last_id Last item id for adding receivers
813 * @param boolean $forum_mode "true" means that we are sending content to a forum
814 * @return array with inboxes
815 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
816 * @throws \ImagickException
818 public static function fetchTargetInboxes($item, $uid, $personal = false, $last_id = 0, $forum_mode = false)
820 $permissions = self::createPermissionBlockForItem($item, true, $last_id, $forum_mode);
821 if (empty($permissions)) {
827 if ($item['gravity'] == GRAVITY_ACTIVITY) {
828 $item_profile = APContact::getByURL($item['author-link'], false);
830 $item_profile = APContact::getByURL($item['owner-link'], false);
833 if (empty($item_profile)) {
837 $profile_uid = User::getIdForURL($item_profile['url']);
839 foreach (['to', 'cc', 'bto', 'bcc'] as $element) {
840 if (empty($permissions[$element])) {
844 $blindcopy = in_array($element, ['bto', 'bcc']);
846 foreach ($permissions[$element] as $receiver) {
847 if (empty($receiver) || Network::isUrlBlocked($receiver)) {
851 if ($item_profile && ($receiver == $item_profile['followers']) && ($uid == $profile_uid)) {
852 $inboxes = array_merge($inboxes, self::fetchTargetInboxesforUser($uid, $personal, self::isAPPost($last_id)));
854 $profile = APContact::getByURL($receiver, false);
855 if (!empty($profile)) {
856 $contact = Contact::getByURLForUser($receiver, $uid, false, ['id']);
858 if (empty($profile['sharedinbox']) || $personal || $blindcopy || Contact::isLocal($receiver)) {
859 $target = $profile['inbox'];
861 $target = $profile['sharedinbox'];
863 if (!self::archivedInbox($target)) {
864 $inboxes[$target][] = $contact['id'] ?? 0;
875 * Creates an array in the structure of the item table for a given mail id
877 * @param integer $mail_id
882 public static function ItemArrayFromMail($mail_id, $use_title = false)
884 $mail = DBA::selectFirst('mail', [], ['id' => $mail_id]);
885 if (!DBA::isResult($mail)) {
889 $reply = DBA::selectFirst('mail', ['uri', 'uri-id', 'from-url'], ['parent-uri' => $mail['parent-uri'], 'reply' => false]);
891 // Making the post more compatible for Mastodon by:
892 // - Making it a note and not an article (no title)
893 // - Moving the title into the "summary" field that is used as a "content warning"
896 $mail['body'] = '[abstract]' . $mail['title'] . "[/abstract]\n" . $mail['body'];
900 $mail['author-link'] = $mail['owner-link'] = $mail['from-url'];
901 $mail['owner-id'] = $mail['author-id'];
902 $mail['allow_cid'] = '<'.$mail['contact-id'].'>';
903 $mail['allow_gid'] = '';
904 $mail['deny_cid'] = '';
905 $mail['deny_gid'] = '';
906 $mail['private'] = Item::PRIVATE;
907 $mail['deleted'] = false;
908 $mail['edited'] = $mail['created'];
909 $mail['plink'] = DI::baseUrl() . '/message/' . $mail['id'];
910 $mail['parent-uri'] = $reply['uri'];
911 $mail['parent-uri-id'] = $reply['uri-id'];
912 $mail['parent-author-id'] = Contact::getIdForURL($reply['from-url'], 0, false);
913 $mail['gravity'] = ($mail['reply'] ? GRAVITY_COMMENT: GRAVITY_PARENT);
914 $mail['event-type'] = '';
915 $mail['language'] = '';
922 * Creates an activity array for a given mail id
924 * @param integer $mail_id
925 * @param boolean $object_mode Is the activity item is used inside another object?
927 * @return array of activity
930 public static function createActivityFromMail($mail_id, $object_mode = false)
932 $mail = self::ItemArrayFromMail($mail_id);
936 $object = self::createNote($mail);
939 $data = ['@context' => ActivityPub::CONTEXT];
944 $data['id'] = $mail['uri'] . '/Create';
945 $data['type'] = 'Create';
946 $data['actor'] = $mail['author-link'];
947 $data['published'] = DateTimeFormat::utc($mail['created'] . '+00:00', DateTimeFormat::ATOM);
948 $data['instrument'] = self::getService();
949 $data = array_merge($data, self::createPermissionBlockForItem($mail, true));
951 if (empty($data['to']) && !empty($data['cc'])) {
952 $data['to'] = $data['cc'];
955 if (empty($data['to']) && !empty($data['bcc'])) {
956 $data['to'] = $data['bcc'];
962 $object['to'] = $data['to'];
963 $object['tag'] = [['type' => 'Mention', 'href' => $object['to'][0], 'name' => '']];
965 unset($object['cc']);
966 unset($object['bcc']);
968 $data['directMessage'] = true;
970 $data['object'] = $object;
972 $owner = User::getOwnerDataById($mail['uid']);
974 if (!$object_mode && !empty($owner)) {
975 return LDSignature::sign($data, $owner);
982 * Returns the activity type of a given item
986 * @return string with activity type
987 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
988 * @throws \ImagickException
990 private static function getTypeOfItem($item)
994 // Only check for a reshare, if it is a real reshare and no quoted reshare
995 if (strpos($item['body'], "[share") === 0) {
996 $announce = self::getAnnounceArray($item);
997 $reshared = !empty($announce);
1002 } elseif ($item['verb'] == Activity::POST) {
1003 if ($item['created'] == $item['edited']) {
1008 } elseif ($item['verb'] == Activity::LIKE) {
1010 } elseif ($item['verb'] == Activity::DISLIKE) {
1012 } elseif ($item['verb'] == Activity::ATTEND) {
1014 } elseif ($item['verb'] == Activity::ATTENDNO) {
1016 } elseif ($item['verb'] == Activity::ATTENDMAYBE) {
1017 $type = 'TentativeAccept';
1018 } elseif ($item['verb'] == Activity::FOLLOW) {
1020 } elseif ($item['verb'] == Activity::TAG) {
1022 } elseif ($item['verb'] == Activity::ANNOUNCE) {
1032 * Creates the activity or fetches it from the cache
1034 * @param integer $item_id
1035 * @param boolean $force Force new cache entry
1037 * @return array with the activity
1038 * @throws \Exception
1040 public static function createCachedActivityFromItem($item_id, $force = false)
1042 $cachekey = 'APDelivery:createActivity:' . $item_id;
1045 $data = DI::cache()->get($cachekey);
1046 if (!is_null($data)) {
1051 $data = self::createActivityFromItem($item_id);
1053 DI::cache()->set($cachekey, $data, Duration::QUARTER_HOUR);
1058 * Creates an activity array for a given item id
1060 * @param integer $item_id
1061 * @param boolean $object_mode Is the activity item is used inside another object?
1063 * @return false|array
1064 * @throws \Exception
1066 public static function createActivityFromItem(int $item_id, bool $object_mode = false)
1068 Logger::info('Fetching activity', ['item' => $item_id]);
1069 $item = Post::selectFirst(Item::DELIVER_FIELDLIST, ['id' => $item_id, 'parent-network' => Protocol::NATIVE_SUPPORT]);
1070 if (!DBA::isResult($item)) {
1074 // In case of a forum post ensure to return the original post if author and forum are on the same machine
1075 if (($item['gravity'] == GRAVITY_PARENT) && !empty($item['forum_mode'])) {
1076 $author = Contact::getById($item['author-id'], ['nurl']);
1077 if (!empty($author['nurl'])) {
1078 $self = Contact::selectFirst(['uid'], ['nurl' => $author['nurl'], 'self' => true]);
1079 if (!empty($self['uid'])) {
1080 $forum_item = Post::selectFirst(Item::DELIVER_FIELDLIST, ['uri-id' => $item['uri-id'], 'uid' => $self['uid']]);
1081 if (DBA::isResult($forum_item)) {
1082 $item = $forum_item;
1088 if (empty($item['uri-id'])) {
1089 Logger::warning('Item without uri-id', ['item' => $item]);
1093 if (!$item['deleted']) {
1094 $condition = ['item-uri' => $item['uri'], 'protocol' => Conversation::PARCEL_ACTIVITYPUB];
1095 $conversation = DBA::selectFirst('conversation', ['source'], $condition);
1096 if (!$item['origin'] && DBA::isResult($conversation)) {
1097 $data = json_decode($conversation['source'], true);
1098 if (!empty($data['type'])) {
1099 if (in_array($data['type'], ['Create', 'Update'])) {
1101 unset($data['@context']);
1102 unset($data['signature']);
1104 Logger::info('Return stored conversation', ['item' => $item_id]);
1106 } elseif (in_array('as:' . $data['type'], Receiver::CONTENT_TYPES)) {
1107 if (!empty($data['@context'])) {
1108 $context = $data['@context'];
1109 unset($data['@context']);
1111 unset($data['actor']);
1118 $type = self::getTypeOfItem($item);
1120 if (!$object_mode) {
1121 $data = ['@context' => $context ?? ActivityPub::CONTEXT];
1123 if ($item['deleted'] && ($item['gravity'] == GRAVITY_ACTIVITY)) {
1125 } elseif ($item['deleted']) {
1132 if ($type == 'Delete') {
1133 $data['id'] = Item::newURI($item['uid'], $item['guid']) . '/' . $type;;
1134 } elseif (($item['gravity'] == GRAVITY_ACTIVITY) && ($type != 'Undo')) {
1135 $data['id'] = $item['uri'];
1137 $data['id'] = $item['uri'] . '/' . $type;
1140 $data['type'] = $type;
1142 if (($type != 'Announce') || ($item['gravity'] != GRAVITY_PARENT)) {
1143 $data['actor'] = $item['author-link'];
1145 $data['actor'] = $item['owner-link'];
1148 $data['published'] = DateTimeFormat::utc($item['created'] . '+00:00', DateTimeFormat::ATOM);
1150 $data['instrument'] = self::getService();
1152 $data = array_merge($data, self::createPermissionBlockForItem($item, false));
1154 if (in_array($data['type'], ['Create', 'Update', 'Delete'])) {
1155 $data['object'] = $object ?? self::createNote($item);
1156 } elseif ($data['type'] == 'Add') {
1157 $data = self::createAddTag($item, $data);
1158 } elseif ($data['type'] == 'Announce') {
1159 if ($item['verb'] == ACTIVITY::ANNOUNCE) {
1160 $data['object'] = $item['thr-parent'];
1162 $data = self::createAnnounce($item, $data);
1164 } elseif ($data['type'] == 'Follow') {
1165 $data['object'] = $item['parent-uri'];
1166 } elseif ($data['type'] == 'Undo') {
1167 $data['object'] = self::createActivityFromItem($item_id, true);
1169 $data['diaspora:guid'] = $item['guid'];
1170 if (!empty($item['signed_text'])) {
1171 $data['diaspora:like'] = $item['signed_text'];
1173 $data['object'] = $item['thr-parent'];
1176 if (!empty($item['contact-uid'])) {
1177 $uid = $item['contact-uid'];
1179 $uid = $item['uid'];
1182 $owner = User::getOwnerDataById($uid);
1184 Logger::info('Fetched activity', ['item' => $item_id, 'uid' => $uid]);
1186 // We don't sign if we aren't the actor. This is important for relaying content especially for forums
1187 if (!$object_mode && !empty($owner) && ($data['actor'] == $owner['url'])) {
1188 return LDSignature::sign($data, $owner);
1193 /// @todo Create "conversation" entry
1197 * Creates a location entry for a given item array
1199 * @param array $item
1201 * @return array with location array
1203 private static function createLocation($item)
1205 $location = ['type' => 'Place'];
1207 if (!empty($item['location'])) {
1208 $location['name'] = $item['location'];
1213 if (empty($item['coord'])) {
1214 $coord = Map::getCoordinates($item['location']);
1216 $coords = explode(' ', $item['coord']);
1217 if (count($coords) == 2) {
1218 $coord = ['lat' => $coords[0], 'lon' => $coords[1]];
1222 if (!empty($coord['lat']) && !empty($coord['lon'])) {
1223 $location['latitude'] = $coord['lat'];
1224 $location['longitude'] = $coord['lon'];
1231 * Returns a tag array for a given item array
1233 * @param array $item
1235 * @return array of tags
1236 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1238 private static function createTagList($item)
1242 $terms = Tag::getByURIId($item['uri-id'], [Tag::HASHTAG, Tag::MENTION, Tag::IMPLICIT_MENTION, Tag::EXCLUSIVE_MENTION]);
1243 foreach ($terms as $term) {
1244 if ($term['type'] == Tag::HASHTAG) {
1245 $url = DI::baseUrl() . '/search?tag=' . urlencode($term['name']);
1246 $tags[] = ['type' => 'Hashtag', 'href' => $url, 'name' => '#' . $term['name']];
1248 $contact = Contact::getByURL($term['url'], false, ['addr']);
1249 if (empty($contact)) {
1252 if (!empty($contact['addr'])) {
1253 $mention = '@' . $contact['addr'];
1255 $mention = '@' . $term['url'];
1258 $tags[] = ['type' => 'Mention', 'href' => $term['url'], 'name' => $mention];
1262 $announce = self::getAnnounceArray($item);
1263 // Mention the original author upon commented reshares
1264 if (!empty($announce['comment'])) {
1265 $tags[] = ['type' => 'Mention', 'href' => $announce['actor']['url'], 'name' => '@' . $announce['actor']['addr']];
1272 * Adds attachment data to the JSON document
1274 * @param array $item Data of the item that is to be posted
1275 * @param string $type Object type
1277 * @return array with attachment data
1278 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1280 private static function createAttachmentList($item, $type)
1284 $uriids = [$item['uri-id']];
1285 $shared = BBCode::fetchShareAttributes($item['body']);
1286 if (!empty($shared['guid'])) {
1287 $shared_item = Post::selectFirst(['uri-id'], ['guid' => $shared['guid']]);
1288 if (!empty($shared_item['uri-id'])) {
1289 $uriids[] = $shared_item['uri-id'];
1294 foreach ($uriids as $uriid) {
1295 foreach (Post\Media::getByURIId($uriid, [Post\Media::DOCUMENT, Post\Media::TORRENT]) as $attachment) {
1296 if (in_array($attachment['url'], $urls)) {
1299 $urls[] = $attachment['url'];
1301 $attach = ['type' => 'Document',
1302 'mediaType' => $attachment['mimetype'],
1303 'url' => $attachment['url'],
1304 'name' => $attachment['description']];
1306 if (!empty($attachment['height'])) {
1307 $attach['height'] = $attachment['height'];
1310 if (!empty($attachment['width'])) {
1311 $attach['width'] = $attachment['width'];
1314 if (!empty($attachment['preview'])) {
1315 $attach['image'] = $attachment['preview'];
1318 $attachments[] = $attach;
1322 if ($type != 'Note') {
1323 return $attachments;
1326 foreach ($uriids as $uriid) {
1327 foreach (Post\Media::getByURIId($uriid, [Post\Media::AUDIO, Post\Media::IMAGE, Post\Media::VIDEO]) as $attachment) {
1328 if (in_array($attachment['url'], $urls)) {
1331 $urls[] = $attachment['url'];
1333 $attach = ['type' => 'Document',
1334 'mediaType' => $attachment['mimetype'],
1335 'url' => $attachment['url'],
1336 'name' => $attachment['description']];
1338 if (!empty($attachment['height'])) {
1339 $attach['height'] = $attachment['height'];
1342 if (!empty($attachment['width'])) {
1343 $attach['width'] = $attachment['width'];
1346 if (!empty($attachment['preview'])) {
1347 $attach['image'] = $attachment['preview'];
1350 $attachments[] = $attach;
1352 // Currently deactivated, since it creates side effects on Mastodon and Pleroma.
1353 // It will be activated, once this cleared.
1355 foreach (Post\Media::getByURIId($uriid, [Post\Media::HTML]) as $attachment) {
1356 if (in_array($attachment['url'], $urls)) {
1359 $urls[] = $attachment['url'];
1361 $attachments[] = ['type' => 'Page',
1362 'mediaType' => $attachment['mimetype'],
1363 'url' => $attachment['url'],
1364 'name' => $attachment['description']];
1368 return $attachments;
1372 * Callback function to replace a Friendica style mention in a mention that is used on AP
1374 * @param array $match Matching values for the callback
1375 * @return string Replaced mention
1376 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1378 private static function mentionCallback($match)
1380 if (empty($match[1])) {
1384 $data = Contact::getByURL($match[1], false, ['url', 'alias', 'nick']);
1385 if (empty($data['nick'])) {
1389 return '[url=' . $data['url'] . ']@' . $data['nick'] . '[/url]';
1393 * Callback function to replace a Friendica style mention in a mention for a summary
1395 * @param array $match Matching values for the callback
1396 * @return string Replaced mention
1397 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1399 private static function mentionAddrCallback($match)
1401 if (empty($match[1])) {
1405 $data = Contact::getByURL($match[1], false, ['addr']);
1406 if (empty($data['addr'])) {
1410 return '@' . $data['addr'];
1414 * Remove image elements since they are added as attachment
1416 * @param string $body
1418 * @return string with removed images
1420 private static function removePictures($body)
1422 // Simplify image codes
1423 $body = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '[img]$3[/img]', $body);
1424 $body = preg_replace("/\[img\=(.*?)\](.*?)\[\/img\]/ism", '[img]$1[/img]', $body);
1426 // Now remove local links
1427 $body = preg_replace_callback(
1428 '/\[url=([^\[\]]*)\]\[img\](.*)\[\/img\]\[\/url\]/Usi',
1430 // We remove the link when it is a link to a local photo page
1431 if (Photo::isLocalPage($match[1])) {
1434 // otherwise we just return the link
1435 return '[url]' . $match[1] . '[/url]';
1440 // Remove all pictures
1441 $body = preg_replace("/\[img\]([^\[\]]*)\[\/img\]/Usi", '', $body);
1447 * Fetches the "context" value for a givem item array from the "conversation" table
1449 * @param array $item
1451 * @return string with context url
1452 * @throws \Exception
1454 private static function fetchContextURLForItem($item)
1456 $conversation = DBA::selectFirst('conversation', ['conversation-href', 'conversation-uri'], ['item-uri' => $item['parent-uri']]);
1457 if (DBA::isResult($conversation) && !empty($conversation['conversation-href'])) {
1458 $context_uri = $conversation['conversation-href'];
1459 } elseif (DBA::isResult($conversation) && !empty($conversation['conversation-uri'])) {
1460 $context_uri = $conversation['conversation-uri'];
1462 $context_uri = $item['parent-uri'] . '#context';
1464 return $context_uri;
1468 * Returns if the post contains sensitive content ("nsfw")
1470 * @param integer $uri_id
1473 * @throws \Exception
1475 private static function isSensitive($uri_id)
1477 return DBA::exists('tag-view', ['uri-id' => $uri_id, 'name' => 'nsfw']);
1481 * Creates event data
1483 * @param array $item
1485 * @return array with the event data
1486 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1488 private static function createEvent($item)
1491 $event['name'] = $item['event-summary'];
1492 $event['content'] = BBCode::convert($item['event-desc'], false, BBCode::ACTIVITYPUB);
1493 $event['startTime'] = DateTimeFormat::utc($item['event-start'] . '+00:00', DateTimeFormat::ATOM);
1495 if (!$item['event-nofinish']) {
1496 $event['endTime'] = DateTimeFormat::utc($item['event-finish'] . '+00:00', DateTimeFormat::ATOM);
1499 if (!empty($item['event-location'])) {
1500 $item['location'] = $item['event-location'];
1501 $event['location'] = self::createLocation($item);
1504 $event['dfrn:adjust'] = (bool)$item['event-adjust'];
1510 * Creates a note/article object array
1512 * @param array $item
1514 * @return array with the object data
1515 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1516 * @throws \ImagickException
1518 public static function createNote($item)
1524 if ($item['event-type'] == 'event') {
1526 } elseif (!empty($item['title'])) {
1532 if ($item['deleted']) {
1533 $type = 'Tombstone';
1537 $data['id'] = $item['uri'];
1538 $data['type'] = $type;
1540 if ($item['deleted']) {
1544 $data['summary'] = BBCode::toPlaintext(BBCode::getAbstract($item['body'], Protocol::ACTIVITYPUB));
1546 if ($item['uri'] != $item['thr-parent']) {
1547 $data['inReplyTo'] = $item['thr-parent'];
1549 $data['inReplyTo'] = null;
1552 $data['diaspora:guid'] = $item['guid'];
1553 $data['published'] = DateTimeFormat::utc($item['created'] . '+00:00', DateTimeFormat::ATOM);
1555 if ($item['created'] != $item['edited']) {
1556 $data['updated'] = DateTimeFormat::utc($item['edited'] . '+00:00', DateTimeFormat::ATOM);
1559 $data['url'] = $item['plink'];
1560 $data['attributedTo'] = $item['author-link'];
1561 $data['sensitive'] = self::isSensitive($item['uri-id']);
1562 $data['context'] = self::fetchContextURLForItem($item);
1564 if (!empty($item['title'])) {
1565 $data['name'] = BBCode::toPlaintext($item['title'], false);
1568 $permission_block = self::createPermissionBlockForItem($item, false);
1570 $body = $item['body'];
1572 if ($type == 'Note') {
1573 $body = $item['raw-body'] ?? self::removePictures($body);
1577 * @todo Improve the automated summary
1578 * This part is currently deactivated. The automated summary seems to be more
1579 * confusing than helping. But possibly we will find a better way.
1580 * So the code is left here for now as a reminder
1582 * } elseif (($type == 'Article') && empty($data['summary'])) {
1583 * $regexp = "/[@!]\[url\=([^\[\]]*)\].*?\[\/url\]/ism";
1584 * $summary = preg_replace_callback($regexp, ['self', 'mentionAddrCallback'], $body);
1585 * $data['summary'] = BBCode::toPlaintext(Plaintext::shorten(self::removePictures($summary), 1000));
1589 if (empty($item['uid']) || !Feature::isEnabled($item['uid'], 'explicit_mentions')) {
1590 $body = self::prependMentions($body, $item['uri-id'], $item['author-link']);
1593 if ($type == 'Event') {
1594 $data = array_merge($data, self::createEvent($item));
1596 $regexp = "/[@!]\[url\=([^\[\]]*)\].*?\[\/url\]/ism";
1597 $body = preg_replace_callback($regexp, ['self', 'mentionCallback'], $body);
1599 $data['content'] = BBCode::convert($body, false, BBCode::ACTIVITYPUB);
1602 // The regular "content" field does contain a minimized HTML. This is done since systems like
1603 // Mastodon has got problems with - for example - embedded pictures.
1604 // The contentMap does contain the unmodified HTML.
1605 $language = self::getLanguage($item);
1606 if (!empty($language)) {
1607 $regexp = "/[@!]\[url\=([^\[\]]*)\].*?\[\/url\]/ism";
1608 $richbody = preg_replace_callback($regexp, ['self', 'mentionCallback'], $item['body']);
1609 $richbody = BBCode::removeAttachment($richbody);
1611 $data['contentMap'][$language] = BBCode::convert($richbody, false, BBCode::EXTERNAL);
1614 $data['source'] = ['content' => $item['body'], 'mediaType' => "text/bbcode"];
1616 if (!empty($item['signed_text']) && ($item['uri'] != $item['thr-parent'])) {
1617 $data['diaspora:comment'] = $item['signed_text'];
1620 $data['attachment'] = self::createAttachmentList($item, $type);
1621 $data['tag'] = self::createTagList($item);
1623 if (empty($data['location']) && (!empty($item['coord']) || !empty($item['location']))) {
1624 $data['location'] = self::createLocation($item);
1627 if (!empty($item['app'])) {
1628 $data['generator'] = ['type' => 'Application', 'name' => $item['app']];
1631 $data = array_merge($data, $permission_block);
1637 * Fetches the language from the post, the user or the system.
1639 * @param array $item
1641 * @return string language string
1643 private static function getLanguage(array $item)
1645 // Try to fetch the language from the post itself
1646 if (!empty($item['language'])) {
1647 $languages = array_keys(json_decode($item['language'], true));
1648 if (!empty($languages[0])) {
1649 return $languages[0];
1653 // Otherwise use the user's language
1654 if (!empty($item['uid'])) {
1655 $user = DBA::selectFirst('user', ['language'], ['uid' => $item['uid']]);
1656 if (!empty($user['language'])) {
1657 return $user['language'];
1661 // And finally just use the system language
1662 return DI::config()->get('system', 'language');
1666 * Creates an an "add tag" entry
1668 * @param array $item
1669 * @param array $data activity data
1671 * @return array with activity data for adding tags
1672 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1673 * @throws \ImagickException
1675 private static function createAddTag($item, $data)
1677 $object = XML::parseString($item['object']);
1678 $target = XML::parseString($item["target"]);
1680 $data['diaspora:guid'] = $item['guid'];
1681 $data['actor'] = $item['author-link'];
1682 $data['target'] = (string)$target->id;
1683 $data['summary'] = BBCode::toPlaintext($item['body']);
1684 $data['object'] = ['id' => (string)$object->id, 'type' => 'tag', 'name' => (string)$object->title, 'content' => (string)$object->content];
1690 * Creates an announce object entry
1692 * @param array $item
1693 * @param array $data activity data
1695 * @return array with activity data
1696 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1697 * @throws \ImagickException
1699 private static function createAnnounce($item, $data)
1701 $orig_body = $item['body'];
1702 $announce = self::getAnnounceArray($item);
1703 if (empty($announce)) {
1704 $data['type'] = 'Create';
1705 $data['object'] = self::createNote($item);
1709 if (empty($announce['comment'])) {
1710 // Pure announce, without a quote
1711 $data['type'] = 'Announce';
1712 $data['object'] = $announce['object']['uri'];
1717 $data['type'] = 'Create';
1718 $item['body'] = $announce['comment'] . "\n" . $announce['object']['plink'];
1719 $data['object'] = self::createNote($item);
1721 /// @todo Finally descide how to implement this in AP. This is a possible way:
1722 $data['object']['attachment'][] = self::createNote($announce['object']);
1724 $data['object']['source']['content'] = $orig_body;
1729 * Return announce related data if the item is an annunce
1731 * @param array $item
1735 public static function getAnnounceArray($item)
1737 $reshared = Item::getShareArray($item);
1738 if (empty($reshared['guid'])) {
1742 $reshared_item = Post::selectFirst(Item::DELIVER_FIELDLIST, ['guid' => $reshared['guid']]);
1743 if (!DBA::isResult($reshared_item)) {
1747 if (!in_array($reshared_item['network'], [Protocol::ACTIVITYPUB, Protocol::DFRN])) {
1751 $profile = APContact::getByURL($reshared_item['author-link'], false);
1752 if (empty($profile)) {
1756 return ['object' => $reshared_item, 'actor' => $profile, 'comment' => $reshared['comment']];
1760 * Checks if the provided item array is an announce
1762 * @param array $item
1766 public static function isAnnounce($item)
1768 if (!empty($item['verb']) && ($item['verb'] == Activity::ANNOUNCE)) {
1772 $announce = self::getAnnounceArray($item);
1773 if (empty($announce)) {
1777 return empty($announce['comment']);
1781 * Creates an activity id for a given contact id
1783 * @param integer $cid Contact ID of target
1785 * @return bool|string activity id
1787 public static function activityIDFromContact($cid)
1789 $contact = DBA::selectFirst('contact', ['uid', 'id', 'created'], ['id' => $cid]);
1790 if (!DBA::isResult($contact)) {
1794 $hash = hash('ripemd128', $contact['uid'].'-'.$contact['id'].'-'.$contact['created']);
1795 $uuid = substr($hash, 0, 8). '-' . substr($hash, 8, 4) . '-' . substr($hash, 12, 4) . '-' . substr($hash, 16, 4) . '-' . substr($hash, 20, 12);
1796 return DI::baseUrl() . '/activity/' . $uuid;
1800 * Transmits a contact suggestion to a given inbox
1802 * @param integer $uid User ID
1803 * @param string $inbox Target inbox
1804 * @param integer $suggestion_id Suggestion ID
1806 * @return boolean was the transmission successful?
1807 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1809 public static function sendContactSuggestion($uid, $inbox, $suggestion_id)
1811 $owner = User::getOwnerDataById($uid);
1813 $suggestion = DI::fsuggest()->getById($suggestion_id);
1815 $data = ['@context' => ActivityPub::CONTEXT,
1816 'id' => DI::baseUrl() . '/activity/' . System::createGUID(),
1817 'type' => 'Announce',
1818 'actor' => $owner['url'],
1819 'object' => $suggestion->url,
1820 'content' => $suggestion->note,
1821 'instrument' => self::getService(),
1822 'to' => [ActivityPub::PUBLIC_COLLECTION],
1825 $signed = LDSignature::sign($data, $owner);
1827 Logger::log('Deliver profile deletion for user ' . $uid . ' to ' . $inbox . ' via ActivityPub', Logger::DEBUG);
1828 return HTTPSignature::transmit($signed, $inbox, $uid);
1832 * Transmits a profile relocation 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 sendProfileRelocation($uid, $inbox)
1842 $owner = User::getOwnerDataById($uid);
1844 $data = ['@context' => ActivityPub::CONTEXT,
1845 'id' => DI::baseUrl() . '/activity/' . System::createGUID(),
1846 'type' => 'dfrn:relocate',
1847 'actor' => $owner['url'],
1848 'object' => $owner['url'],
1849 'published' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
1850 'instrument' => self::getService(),
1851 'to' => [ActivityPub::PUBLIC_COLLECTION],
1854 $signed = LDSignature::sign($data, $owner);
1856 Logger::log('Deliver profile relocation for user ' . $uid . ' to ' . $inbox . ' via ActivityPub', Logger::DEBUG);
1857 return HTTPSignature::transmit($signed, $inbox, $uid);
1861 * Transmits a profile deletion to a given inbox
1863 * @param integer $uid User ID
1864 * @param string $inbox Target inbox
1866 * @return boolean was the transmission successful?
1867 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1869 public static function sendProfileDeletion($uid, $inbox)
1871 $owner = User::getOwnerDataById($uid);
1873 if (empty($owner)) {
1874 Logger::error('No owner data found, the deletion message cannot be processed.', ['user' => $uid]);
1878 if (empty($owner['uprvkey'])) {
1879 Logger::error('No private key for owner found, the deletion message cannot be processed.', ['user' => $uid]);
1883 $data = ['@context' => ActivityPub::CONTEXT,
1884 'id' => DI::baseUrl() . '/activity/' . System::createGUID(),
1886 'actor' => $owner['url'],
1887 'object' => $owner['url'],
1888 'published' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
1889 'instrument' => self::getService(),
1890 'to' => [ActivityPub::PUBLIC_COLLECTION],
1893 $signed = LDSignature::sign($data, $owner);
1895 Logger::log('Deliver profile deletion for user ' . $uid . ' to ' . $inbox . ' via ActivityPub', Logger::DEBUG);
1896 return HTTPSignature::transmit($signed, $inbox, $uid);
1900 * Transmits a profile change to a given inbox
1902 * @param integer $uid User ID
1903 * @param string $inbox Target inbox
1905 * @return boolean was the transmission successful?
1906 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1907 * @throws \ImagickException
1909 public static function sendProfileUpdate($uid, $inbox)
1911 $owner = User::getOwnerDataById($uid);
1912 $profile = APContact::getByURL($owner['url']);
1914 $data = ['@context' => ActivityPub::CONTEXT,
1915 'id' => DI::baseUrl() . '/activity/' . System::createGUID(),
1917 'actor' => $owner['url'],
1918 'object' => self::getProfile($uid),
1919 'published' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
1920 'instrument' => self::getService(),
1921 'to' => [$profile['followers']],
1924 $signed = LDSignature::sign($data, $owner);
1926 Logger::log('Deliver profile update for user ' . $uid . ' to ' . $inbox . ' via ActivityPub', Logger::DEBUG);
1927 return HTTPSignature::transmit($signed, $inbox, $uid);
1931 * Transmits a given activity to a target
1933 * @param string $activity Type name
1934 * @param string $target Target profile
1935 * @param integer $uid User ID
1937 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1938 * @throws \ImagickException
1939 * @throws \Exception
1941 public static function sendActivity($activity, $target, $uid, $id = '')
1943 $profile = APContact::getByURL($target);
1944 if (empty($profile['inbox'])) {
1945 Logger::warning('No inbox found for target', ['target' => $target, 'profile' => $profile]);
1949 $owner = User::getOwnerDataById($uid);
1952 $id = DI::baseUrl() . '/activity/' . System::createGUID();
1955 $data = ['@context' => ActivityPub::CONTEXT,
1957 'type' => $activity,
1958 'actor' => $owner['url'],
1959 'object' => $profile['url'],
1960 'instrument' => self::getService(),
1961 'to' => [$profile['url']]];
1963 Logger::log('Sending activity ' . $activity . ' to ' . $target . ' for user ' . $uid, Logger::DEBUG);
1965 $signed = LDSignature::sign($data, $owner);
1966 return HTTPSignature::transmit($signed, $profile['inbox'], $uid);
1970 * Transmits a "follow object" activity to a target
1971 * This is a preparation for sending automated "follow" requests when receiving "Announce" messages
1973 * @param string $object Object URL
1974 * @param string $target Target profile
1975 * @param integer $uid User ID
1977 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1978 * @throws \ImagickException
1979 * @throws \Exception
1981 public static function sendFollowObject($object, $target, $uid = 0)
1983 $profile = APContact::getByURL($target);
1984 if (empty($profile['inbox'])) {
1985 Logger::warning('No inbox found for target', ['target' => $target, 'profile' => $profile]);
1990 // Fetch the list of administrators
1991 $admin_mail = explode(',', str_replace(' ', '', DI::config()->get('config', 'admin_email')));
1993 // We need to use some user as a sender. It doesn't care who it will send. We will use an administrator account.
1994 $condition = ['verified' => true, 'blocked' => false, 'account_removed' => false, 'account_expired' => false, 'email' => $admin_mail];
1995 $first_user = DBA::selectFirst('user', ['uid'], $condition);
1996 $uid = $first_user['uid'];
1999 $condition = ['verb' => Activity::FOLLOW, 'uid' => 0, 'parent-uri' => $object,
2000 'author-id' => Contact::getPublicIdByUserId($uid)];
2001 if (Post::exists($condition)) {
2002 Logger::log('Follow for ' . $object . ' for user ' . $uid . ' does already exist.', Logger::DEBUG);
2006 $owner = User::getOwnerDataById($uid);
2008 $data = ['@context' => ActivityPub::CONTEXT,
2009 'id' => DI::baseUrl() . '/activity/' . System::createGUID(),
2011 'actor' => $owner['url'],
2012 'object' => $object,
2013 'instrument' => self::getService(),
2014 'to' => [$profile['url']]];
2016 Logger::log('Sending follow ' . $object . ' to ' . $target . ' for user ' . $uid, Logger::DEBUG);
2018 $signed = LDSignature::sign($data, $owner);
2019 return HTTPSignature::transmit($signed, $profile['inbox'], $uid);
2023 * Transmit a message that the contact request had been accepted
2025 * @param string $target Target profile
2027 * @param integer $uid User ID
2028 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2029 * @throws \ImagickException
2031 public static function sendContactAccept($target, $id, $uid)
2033 $profile = APContact::getByURL($target);
2034 if (empty($profile['inbox'])) {
2035 Logger::warning('No inbox found for target', ['target' => $target, 'profile' => $profile]);
2039 $owner = User::getOwnerDataById($uid);
2040 $data = ['@context' => ActivityPub::CONTEXT,
2041 'id' => DI::baseUrl() . '/activity/' . System::createGUID(),
2043 'actor' => $owner['url'],
2045 'id' => (string)$id,
2047 'actor' => $profile['url'],
2048 'object' => $owner['url']
2050 'instrument' => self::getService(),
2051 'to' => [$profile['url']]];
2053 Logger::debug('Sending accept to ' . $target . ' for user ' . $uid . ' with id ' . $id);
2055 $signed = LDSignature::sign($data, $owner);
2056 HTTPSignature::transmit($signed, $profile['inbox'], $uid);
2060 * Reject a contact request or terminates the contact relation
2062 * @param string $target Target profile
2064 * @param integer $uid User ID
2065 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2066 * @throws \ImagickException
2068 public static function sendContactReject($target, $id, $uid)
2070 $profile = APContact::getByURL($target);
2071 if (empty($profile['inbox'])) {
2072 Logger::warning('No inbox found for target', ['target' => $target, 'profile' => $profile]);
2076 $owner = User::getOwnerDataById($uid);
2077 $data = ['@context' => ActivityPub::CONTEXT,
2078 'id' => DI::baseUrl() . '/activity/' . System::createGUID(),
2080 'actor' => $owner['url'],
2082 'id' => (string)$id,
2084 'actor' => $profile['url'],
2085 'object' => $owner['url']
2087 'instrument' => self::getService(),
2088 'to' => [$profile['url']]];
2090 Logger::debug('Sending reject to ' . $target . ' for user ' . $uid . ' with id ' . $id);
2092 $signed = LDSignature::sign($data, $owner);
2093 HTTPSignature::transmit($signed, $profile['inbox'], $uid);
2097 * Transmits a message that we don't want to follow this contact anymore
2099 * @param string $target Target profile
2100 * @param integer $uid User ID
2101 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2102 * @throws \ImagickException
2103 * @throws \Exception
2104 * @return bool success
2106 public static function sendContactUndo($target, $cid, $uid)
2108 $profile = APContact::getByURL($target);
2109 if (empty($profile['inbox'])) {
2110 Logger::warning('No inbox found for target', ['target' => $target, 'profile' => $profile]);
2114 $object_id = self::activityIDFromContact($cid);
2115 if (empty($object_id)) {
2119 $id = DI::baseUrl() . '/activity/' . System::createGUID();
2121 $owner = User::getOwnerDataById($uid);
2122 $data = ['@context' => ActivityPub::CONTEXT,
2125 'actor' => $owner['url'],
2126 'object' => ['id' => $object_id, 'type' => 'Follow',
2127 'actor' => $owner['url'],
2128 'object' => $profile['url']],
2129 'instrument' => self::getService(),
2130 'to' => [$profile['url']]];
2132 Logger::log('Sending undo to ' . $target . ' for user ' . $uid . ' with id ' . $id, Logger::DEBUG);
2134 $signed = LDSignature::sign($data, $owner);
2135 return HTTPSignature::transmit($signed, $profile['inbox'], $uid);
2138 private static function prependMentions($body, int $uriid, string $authorLink)
2142 foreach (Tag::getByURIId($uriid, [Tag::IMPLICIT_MENTION]) as $tag) {
2143 $profile = Contact::getByURL($tag['url'], false, ['addr', 'contact-type', 'nick']);
2144 if (!empty($profile['addr'])
2145 && $profile['contact-type'] != Contact::TYPE_COMMUNITY
2146 && !strstr($body, $profile['addr'])
2147 && !strstr($body, $tag['url'])
2148 && $tag['url'] !== $authorLink
2150 $mentions[] = '@[url=' . $tag['url'] . ']' . $profile['nick'] . '[/url]';
2154 $mentions[] = $body;
2156 return implode(' ', $mentions);