3 * @copyright Copyright (C) 2020, Friendica
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\Item;
37 use Friendica\Model\ItemURI;
38 use Friendica\Model\Profile;
39 use Friendica\Model\Photo;
40 use Friendica\Model\Post;
41 use Friendica\Model\Tag;
42 use Friendica\Model\User;
43 use Friendica\Protocol\Activity;
44 use Friendica\Protocol\ActivityPub;
45 use Friendica\Protocol\Relay;
46 use Friendica\Util\DateTimeFormat;
47 use Friendica\Util\HTTPSignature;
48 use Friendica\Util\JsonLD;
49 use Friendica\Util\LDSignature;
50 use Friendica\Util\Map;
51 use Friendica\Util\Network;
52 use Friendica\Util\XML;
54 require_once 'include/api.php';
55 require_once 'mod/share.php';
58 * ActivityPub Transmitter Protocol class
66 * Add relay servers to the list of inboxes
68 * @param array $inboxes
69 * @return array inboxes with added relay servers
71 public static function addRelayServerInboxes(array $inboxes = [])
73 $contacts = DBA::select('apcontact', ['inbox'],
74 ["`type` = ? AND `url` IN (SELECT `url` FROM `contact` WHERE `uid` = ? AND `rel` IN (?, ?))",
75 'Application', 0, Contact::FOLLOWER, Contact::FRIEND]);
76 while ($contact = DBA::fetch($contacts)) {
77 $inboxes[$contact['inbox']] = $contact['inbox'];
79 DBA::close($contacts);
85 * Add relay servers to the list of inboxes
87 * @param array $inboxes
88 * @return array inboxes with added relay servers
90 public static function addRelayServerInboxesForItem(int $item_id, array $inboxes = [])
92 $item = Item::selectFirst(['uid'], ['id' => $item_id]);
97 $relays = Relay::getList($item_id, [], [Protocol::ACTIVITYPUB]);
102 foreach ($relays as $relay) {
103 $contact = Contact::getByURLForUser($relay['url'], $item['uid'], false, ['id']);
104 $inboxes[$relay['batch']][] = $contact['id'] ?? 0;
110 * Subscribe to a relay
112 * @param string $url Subscribe actor url
113 * @return bool success
115 public static function sendRelayFollow(string $url)
117 $contact = Contact::getByURL($url);
118 if (empty($contact)) {
122 $activity_id = ActivityPub\Transmitter::activityIDFromContact($contact['id']);
123 $success = ActivityPub\Transmitter::sendActivity('Follow', $url, 0, $activity_id);
125 $rel = $contact['rel'] == Contact::SHARING ? Contact::FRIEND : Contact::FOLLOWER;
126 DBA::update('contact', ['rel' => $rel], ['id' => $contact['id']]);
133 * Unsubscribe from a relay
135 * @param string $url Subscribe actor url
136 * @param bool $force Set the relay status as non follower even if unsubscribe hadn't worked
137 * @return bool success
139 public static function sendRelayUndoFollow(string $url, bool $force = false)
141 $contact = Contact::getByURL($url);
142 if (empty($contact)) {
146 $success = self::sendContactUndo($url, $contact['id'], 0);
147 if ($success || $force) {
148 $rel = $contact['rel'] == Contact::FRIEND ? Contact::SHARING : Contact::NOTHING;
149 DBA::update('contact', ['rel' => $rel], ['id' => $contact['id']]);
156 * Collects a list of contacts of the given owner
158 * @param array $owner Owner array
159 * @param int|array $rel The relevant value(s) contact.rel should match
160 * @param string $module The name of the relevant AP endpoint module (followers|following)
161 * @param integer $page Page number
163 * @return array of owners
166 public static function getContacts($owner, $rel, $module, $page = null)
170 'uid' => $owner['uid'],
178 $condition = DBA::buildCondition($parameters);
180 $sql = "SELECT COUNT(*) as `count`
182 JOIN `apcontact` ON `apcontact`.`url` = `contact`.`url`
185 $contacts = DBA::fetchFirst($sql, ...$parameters);
187 $modulePath = '/' . $module . '/';
189 $data = ['@context' => ActivityPub::CONTEXT];
190 $data['id'] = DI::baseUrl() . $modulePath . $owner['nickname'];
191 $data['type'] = 'OrderedCollection';
192 $data['totalItems'] = $contacts['count'];
194 // When we hide our friends we will only show the pure number but don't allow more.
195 $profile = Profile::getByUID($owner['uid']);
196 if (!empty($profile['hide-friends'])) {
201 $data['first'] = DI::baseUrl() . $modulePath . $owner['nickname'] . '?page=1';
203 $data['type'] = 'OrderedCollectionPage';
206 $sql = "SELECT `contact`.`url`
208 JOIN `apcontact` ON `apcontact`.`url` = `contact`.`url`
212 $parameters[] = ($page - 1) * 100;
215 $contacts = DBA::p($sql, ...$parameters);
216 while ($contact = DBA::fetch($contacts)) {
217 $list[] = $contact['url'];
219 DBA::close($contacts);
222 $data['next'] = DI::baseUrl() . $modulePath . $owner['nickname'] . '?page=' . ($page + 1);
225 $data['partOf'] = DI::baseUrl() . $modulePath . $owner['nickname'];
227 $data['orderedItems'] = $list;
234 * Public posts for the given owner
236 * @param array $owner Owner array
237 * @param integer $page Page number
238 * @param string $requester URL of requesting account
240 * @return array of posts
241 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
242 * @throws \ImagickException
244 public static function getOutbox($owner, $page = null, $requester = '')
246 $public_contact = Contact::getIdForURL($owner['url']);
247 $condition = ['uid' => 0, 'contact-id' => $public_contact,
248 'private' => [Item::PUBLIC, Item::UNLISTED]];
250 if (!empty($requester)) {
251 $requester_id = Contact::getIdForURL($requester, $owner['uid']);
252 if (!empty($requester_id)) {
253 $permissionSets = DI::permissionSet()->selectByContactId($requester_id, $owner['uid']);
254 if (!empty($permissionSets)) {
255 $condition = ['uid' => $owner['uid'], 'origin' => true,
256 'psid' => array_merge($permissionSets->column('id'),
257 [DI::permissionSet()->getIdFromACL($owner['uid'], '', '', '', '')])];
262 $condition = array_merge($condition,
263 ['author-id' => $public_contact,
264 'gravity' => [GRAVITY_PARENT, GRAVITY_COMMENT],
265 'deleted' => false, 'visible' => true, 'moderated' => false]);
267 $count = DBA::count('item', $condition);
269 $data = ['@context' => ActivityPub::CONTEXT];
270 $data['id'] = DI::baseUrl() . '/outbox/' . $owner['nickname'];
271 $data['type'] = 'OrderedCollection';
272 $data['totalItems'] = $count;
275 $data['first'] = DI::baseUrl() . '/outbox/' . $owner['nickname'] . '?page=1';
277 $data['type'] = 'OrderedCollectionPage';
280 $condition['parent-network'] = Protocol::NATIVE_SUPPORT;
282 $items = Item::select(['id'], $condition, ['limit' => [($page - 1) * 20, 20], 'order' => ['created' => true]]);
283 while ($item = Item::fetch($items)) {
284 $activity = self::createActivityFromItem($item['id'], true);
285 $activity['type'] = $activity['type'] == 'Update' ? 'Create' : $activity['type'];
287 // Only list "Create" activity objects here, no reshares
288 if (!empty($activity['object']) && ($activity['type'] == 'Create')) {
289 $list[] = $activity['object'];
294 $data['next'] = DI::baseUrl() . '/outbox/' . $owner['nickname'] . '?page=' . ($page + 1);
297 $data['partOf'] = DI::baseUrl() . '/outbox/' . $owner['nickname'];
299 $data['orderedItems'] = $list;
306 * Return the service array containing information the used software and it's url
308 * @return array with service data
310 private static function getService()
312 return ['type' => 'Service',
313 'name' => FRIENDICA_PLATFORM . " '" . FRIENDICA_CODENAME . "' " . FRIENDICA_VERSION . '-' . DB_UPDATE_VERSION,
314 'url' => DI::baseUrl()->get()];
318 * Return the ActivityPub profile of the given user
320 * @param integer $uid User ID
321 * @return array with profile data
322 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
324 public static function getProfile($uid)
327 $condition = ['uid' => $uid, 'blocked' => false, 'account_expired' => false,
328 'account_removed' => false, 'verified' => true];
329 $fields = ['guid', 'nickname', 'pubkey', 'account-type', 'page-flags'];
330 $user = DBA::selectFirst('user', $fields, $condition);
331 if (!DBA::isResult($user)) {
335 $fields = ['locality', 'region', 'country-name'];
336 $profile = DBA::selectFirst('profile', $fields, ['uid' => $uid]);
337 if (!DBA::isResult($profile)) {
341 $fields = ['name', 'url', 'location', 'about', 'avatar', 'photo'];
342 $contact = DBA::selectFirst('contact', $fields, ['uid' => $uid, 'self' => true]);
343 if (!DBA::isResult($contact)) {
347 $contact = User::getSystemAccount();
348 $user = ['guid' => '', 'nickname' => $contact['nick'], 'pubkey' => $contact['pubkey'],
349 'account-type' => $contact['contact-type'], 'page-flags' => User::PAGE_FLAGS_NORMAL];
350 $profile = ['locality' => '', 'region' => '', 'country-name' => ''];
353 $data = ['@context' => ActivityPub::CONTEXT];
354 $data['id'] = $contact['url'];
356 if (!empty($user['guid'])) {
357 $data['diaspora:guid'] = $user['guid'];
360 $data['type'] = ActivityPub::ACCOUNT_TYPES[$user['account-type']];
363 $data['following'] = DI::baseUrl() . '/following/' . $user['nickname'];
364 $data['followers'] = DI::baseUrl() . '/followers/' . $user['nickname'];
365 $data['inbox'] = DI::baseUrl() . '/inbox/' . $user['nickname'];
366 $data['outbox'] = DI::baseUrl() . '/outbox/' . $user['nickname'];
368 $data['inbox'] = DI::baseUrl() . '/friendica/inbox';
371 $data['preferredUsername'] = $user['nickname'];
372 $data['name'] = $contact['name'];
374 if (!empty($profile['country-name'] . $profile['region'] . $profile['locality'])) {
375 $data['vcard:hasAddress'] = ['@type' => 'vcard:Home', 'vcard:country-name' => $profile['country-name'],
376 'vcard:region' => $profile['region'], 'vcard:locality' => $profile['locality']];
379 if (!empty($contact['about'])) {
380 $data['summary'] = BBCode::convert($contact['about'], false);
383 $data['url'] = $contact['url'];
384 $data['manuallyApprovesFollowers'] = in_array($user['page-flags'], [User::PAGE_FLAGS_NORMAL, User::PAGE_FLAGS_PRVGROUP]);
385 $data['publicKey'] = ['id' => $contact['url'] . '#main-key',
386 'owner' => $contact['url'],
387 'publicKeyPem' => $user['pubkey']];
388 $data['endpoints'] = ['sharedInbox' => DI::baseUrl() . '/inbox'];
389 $data['icon'] = ['type' => 'Image',
390 'url' => $contact['photo']];
392 $data['generator'] = self::getService();
394 // tags: https://kitty.town/@inmysocks/100656097926961126.json
399 * @param string $username
401 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
403 public static function getDeletedUser($username)
406 '@context' => ActivityPub::CONTEXT,
407 'id' => DI::baseUrl() . '/profile/' . $username,
408 'type' => 'Tombstone',
409 'published' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
410 'updated' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
411 'deleted' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
416 * Returns an array with permissions of a given item array
420 * @return array with permissions
421 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
422 * @throws \ImagickException
424 private static function fetchPermissionBlockFromConversation($item)
426 if (empty($item['thr-parent'])) {
430 $condition = ['item-uri' => $item['thr-parent'], 'protocol' => Conversation::PARCEL_ACTIVITYPUB];
431 $conversation = DBA::selectFirst('conversation', ['source'], $condition);
432 if (!DBA::isResult($conversation)) {
436 $activity = json_decode($conversation['source'], true);
438 $actor = JsonLD::fetchElement($activity, 'actor', 'id');
439 if (!empty($actor)) {
440 $permissions['to'][] = $actor;
441 $profile = APContact::getByURL($actor);
446 $item_profile = APContact::getByURL($item['author-link']);
447 $exclude[] = $item['author-link'];
449 if ($item['gravity'] == GRAVITY_PARENT) {
450 $exclude[] = $item['owner-link'];
453 foreach (['to', 'cc', 'bto', 'bcc'] as $element) {
454 if (empty($activity[$element])) {
457 if (is_string($activity[$element])) {
458 $activity[$element] = [$activity[$element]];
461 foreach ($activity[$element] as $receiver) {
462 if (empty($receiver)) {
466 if (!empty($profile['followers']) && $receiver == $profile['followers'] && !empty($item_profile['followers'])) {
467 $permissions[$element][] = $item_profile['followers'];
468 } elseif (!in_array($receiver, $exclude)) {
469 $permissions[$element][] = $receiver;
477 * Check if the given item id is from ActivityPub
479 * @param integer $item_id
480 * @return boolean "true" if the post is from ActivityPub
482 private static function isAPPost(int $item_id)
484 if (empty($item_id)) {
488 return Item::exists(['id' => $item_id, 'network' => Protocol::ACTIVITYPUB]);
492 * Creates an array of permissions from an item thread
494 * @param array $item Item array
495 * @param boolean $blindcopy addressing via "bcc" or "cc"?
496 * @param integer $last_id Last item id for adding receivers
497 * @param boolean $forum_mode "true" means that we are sending content to a forum
499 * @return array with permission data
500 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
501 * @throws \ImagickException
503 private static function createPermissionBlockForItem($item, $blindcopy, $last_id = 0, $forum_mode = false)
506 $last_id = $item['id'];
511 // Check if we should always deliver our stuff via BCC
512 if (!empty($item['uid'])) {
513 $profile = User::getOwnerDataById($item['uid']);
514 if (!empty($profile)) {
515 $always_bcc = $profile['hide-friends'];
519 if (DI::config()->get('system', 'ap_always_bcc')) {
523 if (self::isAnnounce($item) || DI::config()->get('debug', 'total_ap_delivery') || self::isAPPost($last_id)) {
524 // Will be activated in a later step
525 $networks = Protocol::FEDERATED;
527 // For now only send to these contacts:
528 $networks = [Protocol::ACTIVITYPUB, Protocol::OSTATUS];
531 $data = ['to' => [], 'cc' => [], 'bcc' => []];
533 if ($item['gravity'] == GRAVITY_PARENT) {
534 $actor_profile = APContact::getByURL($item['owner-link']);
536 $actor_profile = APContact::getByURL($item['author-link']);
539 $terms = Tag::getByURIId($item['uri-id'], [Tag::MENTION, Tag::IMPLICIT_MENTION, Tag::EXCLUSIVE_MENTION]);
541 if ($item['private'] != Item::PRIVATE) {
542 // Directly mention the original author upon a quoted reshare.
543 // Else just ensure that the original author receives the reshare.
544 $announce = self::getAnnounceArray($item);
545 if (!empty($announce['comment'])) {
546 $data['to'][] = $announce['actor']['url'];
547 } elseif (!empty($announce)) {
548 $data['cc'][] = $announce['actor']['url'];
551 $data = array_merge($data, self::fetchPermissionBlockFromConversation($item));
553 // Check if the item is completely public or unlisted
554 if ($item['private'] == Item::PUBLIC) {
555 $data['to'][] = ActivityPub::PUBLIC_COLLECTION;
557 $data['cc'][] = ActivityPub::PUBLIC_COLLECTION;
560 foreach ($terms as $term) {
561 $profile = APContact::getByURL($term['url'], false);
562 if (!empty($profile)) {
563 $data['to'][] = $profile['url'];
567 $receiver_list = Item::enumeratePermissions($item, true);
569 foreach ($terms as $term) {
570 $cid = Contact::getIdForURL($term['url'], $item['uid']);
571 if (!empty($cid) && in_array($cid, $receiver_list)) {
572 $contact = DBA::selectFirst('contact', ['url', 'network', 'protocol'], ['id' => $cid]);
573 if (!DBA::isResult($contact) || (!in_array($contact['network'], $networks) && ($contact['protocol'] != Protocol::ACTIVITYPUB))) {
577 if (!empty($profile = APContact::getByURL($contact['url'], false))) {
578 $data['to'][] = $profile['url'];
583 foreach ($receiver_list as $receiver) {
584 $contact = DBA::selectFirst('contact', ['url', 'hidden', 'network', 'protocol'], ['id' => $receiver]);
585 if (!DBA::isResult($contact) || (!in_array($contact['network'], $networks) && ($contact['protocol'] != Protocol::ACTIVITYPUB))) {
589 if (!empty($profile = APContact::getByURL($contact['url'], false))) {
590 if ($contact['hidden'] || $always_bcc) {
591 $data['bcc'][] = $profile['url'];
593 $data['cc'][] = $profile['url'];
599 if (!empty($item['parent'])) {
600 $parents = Item::select(['id', 'author-link', 'owner-link', 'gravity', 'uri'], ['parent' => $item['parent']]);
601 while ($parent = Item::fetch($parents)) {
602 if ($parent['gravity'] == GRAVITY_PARENT) {
603 $profile = APContact::getByURL($parent['owner-link'], false);
604 if (!empty($profile)) {
605 if ($item['gravity'] != GRAVITY_PARENT) {
606 // Comments to forums are directed to the forum
607 // But comments to forums aren't directed to the followers collection
608 // This rule is only valid when the actor isn't the forum.
609 // The forum needs to transmit their content to their followers.
610 if (($profile['type'] == 'Group') && ($profile['url'] != $actor_profile['url'])) {
611 $data['to'][] = $profile['url'];
613 $data['cc'][] = $profile['url'];
614 if (($item['private'] != Item::PRIVATE) && !empty($actor_profile['followers'])) {
615 $data['cc'][] = $actor_profile['followers'];
619 // Public thread parent post always are directed to the followers
620 if (($item['private'] != Item::PRIVATE) && !$forum_mode) {
621 $data['cc'][] = $actor_profile['followers'];
627 // Don't include data from future posts
628 if ($parent['id'] >= $last_id) {
632 $profile = APContact::getByURL($parent['author-link'], false);
633 if (!empty($profile)) {
634 if (($profile['type'] == 'Group') || ($parent['uri'] == $item['thr-parent'])) {
635 $data['to'][] = $profile['url'];
637 $data['cc'][] = $profile['url'];
641 DBA::close($parents);
644 $data['to'] = array_unique($data['to']);
645 $data['cc'] = array_unique($data['cc']);
646 $data['bcc'] = array_unique($data['bcc']);
648 if (($key = array_search($item['author-link'], $data['to'])) !== false) {
649 unset($data['to'][$key]);
652 if (($key = array_search($item['author-link'], $data['cc'])) !== false) {
653 unset($data['cc'][$key]);
656 if (($key = array_search($item['author-link'], $data['bcc'])) !== false) {
657 unset($data['bcc'][$key]);
660 foreach ($data['to'] as $to) {
661 if (($key = array_search($to, $data['cc'])) !== false) {
662 unset($data['cc'][$key]);
665 if (($key = array_search($to, $data['bcc'])) !== false) {
666 unset($data['bcc'][$key]);
670 foreach ($data['cc'] as $cc) {
671 if (($key = array_search($cc, $data['bcc'])) !== false) {
672 unset($data['bcc'][$key]);
676 $receivers = ['to' => array_values($data['to']), 'cc' => array_values($data['cc']), 'bcc' => array_values($data['bcc'])];
679 unset($receivers['bcc']);
686 * Check if an inbox is archived
688 * @param string $url Inbox url
690 * @return boolean "true" if inbox is archived
692 public static function archivedInbox($url)
694 return DBA::exists('inbox-status', ['url' => $url, 'archive' => true]);
698 * Fetches a list of inboxes of followers of a given user
700 * @param integer $uid User ID
701 * @param boolean $personal fetch personal inboxes
702 * @param boolean $all_ap Retrieve all AP enabled inboxes
704 * @return array of follower inboxes
705 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
706 * @throws \ImagickException
708 public static function fetchTargetInboxesforUser($uid, $personal = false, bool $all_ap = false)
714 if (!empty($item['uid'])) {
715 $profile = User::getOwnerDataById($item['uid']);
716 if (!empty($profile)) {
717 $isforum = $profile['account-type'] == User::ACCOUNT_TYPE_COMMUNITY;
721 if (DI::config()->get('debug', 'total_ap_delivery') || $all_ap) {
722 // Will be activated in a later step
723 $networks = Protocol::FEDERATED;
725 // For now only send to these contacts:
726 $networks = [Protocol::ACTIVITYPUB, Protocol::OSTATUS];
729 $condition = ['uid' => $uid, 'archive' => false, 'pending' => false, 'blocked' => false];
732 $condition['rel'] = [Contact::FOLLOWER, Contact::FRIEND];
735 $contacts = DBA::select('contact', ['id', 'url', 'network', 'protocol'], $condition);
736 while ($contact = DBA::fetch($contacts)) {
737 if (Contact::isLocal($contact['url'])) {
741 if (!in_array($contact['network'], $networks) && ($contact['protocol'] != Protocol::ACTIVITYPUB)) {
745 if ($isforum && ($contact['network'] == Protocol::DFRN)) {
749 if (Network::isUrlBlocked($contact['url'])) {
753 $profile = APContact::getByURL($contact['url'], false);
754 if (!empty($profile)) {
755 if (empty($profile['sharedinbox']) || $personal) {
756 $target = $profile['inbox'];
758 $target = $profile['sharedinbox'];
760 if (!self::archivedInbox($target)) {
761 $inboxes[$target][] = $contact['id'];
765 DBA::close($contacts);
771 * Fetches an array of inboxes for the given item and user
773 * @param array $item Item array
774 * @param integer $uid User ID
775 * @param boolean $personal fetch personal inboxes
776 * @param integer $last_id Last item id for adding receivers
777 * @param boolean $forum_mode "true" means that we are sending content to a forum
778 * @return array with inboxes
779 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
780 * @throws \ImagickException
782 public static function fetchTargetInboxes($item, $uid, $personal = false, $last_id = 0, $forum_mode = false)
784 $permissions = self::createPermissionBlockForItem($item, true, $last_id, $forum_mode);
785 if (empty($permissions)) {
791 if ($item['gravity'] == GRAVITY_ACTIVITY) {
792 $item_profile = APContact::getByURL($item['author-link'], false);
794 $item_profile = APContact::getByURL($item['owner-link'], false);
797 if (empty($item_profile)) {
801 $profile_uid = User::getIdForURL($item_profile['url']);
803 foreach (['to', 'cc', 'bto', 'bcc'] as $element) {
804 if (empty($permissions[$element])) {
808 $blindcopy = in_array($element, ['bto', 'bcc']);
810 foreach ($permissions[$element] as $receiver) {
811 if (empty($receiver) || Network::isUrlBlocked($receiver)) {
815 if ($item_profile && ($receiver == $item_profile['followers']) && ($uid == $profile_uid)) {
816 $inboxes = array_merge($inboxes, self::fetchTargetInboxesforUser($uid, $personal, self::isAPPost($last_id)));
818 if (Contact::isLocal($receiver)) {
822 $profile = APContact::getByURL($receiver, false);
823 if (!empty($profile)) {
824 $contact = Contact::getByURLForUser($receiver, $uid, false, ['id']);
826 if (empty($profile['sharedinbox']) || $personal || $blindcopy) {
827 $target = $profile['inbox'];
829 $target = $profile['sharedinbox'];
831 if (!self::archivedInbox($target)) {
832 $inboxes[$target][] = $contact['id'] ?? 0;
843 * Creates an array in the structure of the item table for a given mail id
845 * @param integer $mail_id
850 public static function ItemArrayFromMail($mail_id)
852 $mail = DBA::selectFirst('mail', [], ['id' => $mail_id]);
853 if (!DBA::isResult($mail)) {
857 $mail['uri-id'] = ItemURI::insert(['uri' => $mail['uri'], 'guid' => $mail['guid']]);
859 $reply = DBA::selectFirst('mail', ['uri'], ['parent-uri' => $mail['parent-uri'], 'reply' => false]);
861 // Making the post more compatible for Mastodon by:
862 // - Making it a note and not an article (no title)
863 // - Moving the title into the "summary" field that is used as a "content warning"
864 $mail['body'] = '[abstract]' . $mail['title'] . "[/abstract]\n" . $mail['body'];
867 $mail['author-link'] = $mail['owner-link'] = $mail['from-url'];
868 $mail['allow_cid'] = '<'.$mail['contact-id'].'>';
869 $mail['allow_gid'] = '';
870 $mail['deny_cid'] = '';
871 $mail['deny_gid'] = '';
872 $mail['private'] = true;
873 $mail['deleted'] = false;
874 $mail['edited'] = $mail['created'];
875 $mail['plink'] = $mail['uri'];
876 $mail['thr-parent'] = $reply['uri'];
877 $mail['gravity'] = ($mail['reply'] ? GRAVITY_COMMENT: GRAVITY_PARENT);
879 $mail['event-type'] = '';
887 * Creates an activity array for a given mail id
889 * @param integer $mail_id
890 * @param boolean $object_mode Is the activity item is used inside another object?
892 * @return array of activity
895 public static function createActivityFromMail($mail_id, $object_mode = false)
897 $mail = self::ItemArrayFromMail($mail_id);
901 $object = self::createNote($mail);
904 $data = ['@context' => ActivityPub::CONTEXT];
909 $data['id'] = $mail['uri'] . '/Create';
910 $data['type'] = 'Create';
911 $data['actor'] = $mail['author-link'];
912 $data['published'] = DateTimeFormat::utc($mail['created'] . '+00:00', DateTimeFormat::ATOM);
913 $data['instrument'] = self::getService();
914 $data = array_merge($data, self::createPermissionBlockForItem($mail, true));
916 if (empty($data['to']) && !empty($data['cc'])) {
917 $data['to'] = $data['cc'];
920 if (empty($data['to']) && !empty($data['bcc'])) {
921 $data['to'] = $data['bcc'];
927 $object['to'] = $data['to'];
928 $object['tag'] = [['type' => 'Mention', 'href' => $object['to'][0], 'name' => '']];
930 unset($object['cc']);
931 unset($object['bcc']);
933 $data['directMessage'] = true;
935 $data['object'] = $object;
937 $owner = User::getOwnerDataById($mail['uid']);
939 if (!$object_mode && !empty($owner)) {
940 return LDSignature::sign($data, $owner);
947 * Returns the activity type of a given item
951 * @return string with activity type
952 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
953 * @throws \ImagickException
955 private static function getTypeOfItem($item)
959 // Only check for a reshare, if it is a real reshare and no quoted reshare
960 if (strpos($item['body'], "[share") === 0) {
961 $announce = self::getAnnounceArray($item);
962 $reshared = !empty($announce);
967 } elseif ($item['verb'] == Activity::POST) {
968 if ($item['created'] == $item['edited']) {
973 } elseif ($item['verb'] == Activity::LIKE) {
975 } elseif ($item['verb'] == Activity::DISLIKE) {
977 } elseif ($item['verb'] == Activity::ATTEND) {
979 } elseif ($item['verb'] == Activity::ATTENDNO) {
981 } elseif ($item['verb'] == Activity::ATTENDMAYBE) {
982 $type = 'TentativeAccept';
983 } elseif ($item['verb'] == Activity::FOLLOW) {
985 } elseif ($item['verb'] == Activity::TAG) {
987 } elseif ($item['verb'] == Activity::ANNOUNCE) {
997 * Creates the activity or fetches it from the cache
999 * @param integer $item_id
1000 * @param boolean $force Force new cache entry
1002 * @return array with the activity
1003 * @throws \Exception
1005 public static function createCachedActivityFromItem($item_id, $force = false)
1007 $cachekey = 'APDelivery:createActivity:' . $item_id;
1010 $data = DI::cache()->get($cachekey);
1011 if (!is_null($data)) {
1016 $data = self::createActivityFromItem($item_id);
1018 DI::cache()->set($cachekey, $data, Duration::QUARTER_HOUR);
1023 * Creates an activity array for a given item id
1025 * @param integer $item_id
1026 * @param boolean $object_mode Is the activity item is used inside another object?
1028 * @return false|array
1029 * @throws \Exception
1031 public static function createActivityFromItem(int $item_id, bool $object_mode = false)
1033 Logger::info('Fetching activity', ['item' => $item_id]);
1034 $item = Item::selectFirst([], ['id' => $item_id, 'parent-network' => Protocol::NATIVE_SUPPORT]);
1035 if (!DBA::isResult($item)) {
1039 // In case of a forum post ensure to return the original post if author and forum are on the same machine
1040 if (!empty($item['forum_mode'])) {
1041 $author = Contact::getById($item['author-id'], ['nurl']);
1042 if (!empty($author['nurl'])) {
1043 $self = Contact::selectFirst(['uid'], ['nurl' => $author['nurl'], 'self' => true]);
1044 if (!empty($self['uid'])) {
1045 $forum_item = Item::selectFirst([], ['uri-id' => $item['uri-id'], 'uid' => $self['uid']]);
1046 if (DBA::isResult($item)) {
1047 $item = $forum_item;
1053 if (empty($item['uri-id'])) {
1054 Logger::warning('Item without uri-id', ['item' => $item]);
1058 $condition = ['item-uri' => $item['uri'], 'protocol' => Conversation::PARCEL_ACTIVITYPUB];
1059 $conversation = DBA::selectFirst('conversation', ['source'], $condition);
1060 if (!$item['origin'] && DBA::isResult($conversation)) {
1061 $data = json_decode($conversation['source'], true);
1062 if (!empty($data['type'])) {
1063 if (in_array($data['type'], ['Create', 'Update'])) {
1065 unset($data['@context']);
1066 unset($data['signature']);
1068 Logger::info('Return stored conversation', ['item' => $item_id]);
1070 } elseif (in_array('as:' . $data['type'], Receiver::CONTENT_TYPES)) {
1071 if (!empty($data['@context'])) {
1072 $context = $data['@context'];
1073 unset($data['@context']);
1075 unset($data['actor']);
1081 $type = self::getTypeOfItem($item);
1083 if (!$object_mode) {
1084 $data = ['@context' => $context ?? ActivityPub::CONTEXT];
1086 if ($item['deleted'] && ($item['gravity'] == GRAVITY_ACTIVITY)) {
1088 } elseif ($item['deleted']) {
1095 if (($item['gravity'] == GRAVITY_ACTIVITY) && ($type != 'Undo')) {
1096 $data['id'] = $item['uri'];
1098 $data['id'] = $item['uri'] . '/' . $type;
1101 $data['type'] = $type;
1103 if (($type != 'Announce') || ($item['gravity'] != GRAVITY_PARENT)) {
1104 $data['actor'] = $item['author-link'];
1106 $data['actor'] = $item['owner-link'];
1109 $data['published'] = DateTimeFormat::utc($item['created'] . '+00:00', DateTimeFormat::ATOM);
1111 $data['instrument'] = self::getService();
1113 $data = array_merge($data, self::createPermissionBlockForItem($item, false));
1115 if (in_array($data['type'], ['Create', 'Update', 'Delete'])) {
1116 $data['object'] = $object ?? self::createNote($item);
1117 } elseif ($data['type'] == 'Add') {
1118 $data = self::createAddTag($item, $data);
1119 } elseif ($data['type'] == 'Announce') {
1120 if ($item['verb'] == ACTIVITY::ANNOUNCE) {
1121 $data['object'] = $item['thr-parent'];
1123 $data = self::createAnnounce($item, $data);
1125 } elseif ($data['type'] == 'Follow') {
1126 $data['object'] = $item['parent-uri'];
1127 } elseif ($data['type'] == 'Undo') {
1128 $data['object'] = self::createActivityFromItem($item_id, true);
1130 $data['diaspora:guid'] = $item['guid'];
1131 if (!empty($item['signed_text'])) {
1132 $data['diaspora:like'] = $item['signed_text'];
1134 $data['object'] = $item['thr-parent'];
1137 if (!empty($item['contact-uid'])) {
1138 $uid = $item['contact-uid'];
1140 $uid = $item['uid'];
1143 $owner = User::getOwnerDataById($uid);
1145 Logger::info('Fetched activity', ['item' => $item_id, 'uid' => $uid]);
1147 // We don't sign if we aren't the actor. This is important for relaying content especially for forums
1148 if (!$object_mode && !empty($owner) && ($data['actor'] == $owner['url'])) {
1149 return LDSignature::sign($data, $owner);
1154 /// @todo Create "conversation" entry
1158 * Creates a location entry for a given item array
1160 * @param array $item
1162 * @return array with location array
1164 private static function createLocation($item)
1166 $location = ['type' => 'Place'];
1168 if (!empty($item['location'])) {
1169 $location['name'] = $item['location'];
1174 if (empty($item['coord'])) {
1175 $coord = Map::getCoordinates($item['location']);
1177 $coords = explode(' ', $item['coord']);
1178 if (count($coords) == 2) {
1179 $coord = ['lat' => $coords[0], 'lon' => $coords[1]];
1183 if (!empty($coord['lat']) && !empty($coord['lon'])) {
1184 $location['latitude'] = $coord['lat'];
1185 $location['longitude'] = $coord['lon'];
1192 * Returns a tag array for a given item array
1194 * @param array $item
1196 * @return array of tags
1197 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1199 private static function createTagList($item)
1203 $terms = Tag::getByURIId($item['uri-id'], [Tag::HASHTAG, Tag::MENTION, Tag::IMPLICIT_MENTION, Tag::EXCLUSIVE_MENTION]);
1204 foreach ($terms as $term) {
1205 if ($term['type'] == Tag::HASHTAG) {
1206 $url = DI::baseUrl() . '/search?tag=' . urlencode($term['name']);
1207 $tags[] = ['type' => 'Hashtag', 'href' => $url, 'name' => '#' . $term['name']];
1209 $contact = Contact::getByURL($term['url'], false, ['addr']);
1210 if (empty($contact)) {
1213 if (!empty($contact['addr'])) {
1214 $mention = '@' . $contact['addr'];
1216 $mention = '@' . $term['url'];
1219 $tags[] = ['type' => 'Mention', 'href' => $term['url'], 'name' => $mention];
1223 $announce = self::getAnnounceArray($item);
1224 // Mention the original author upon commented reshares
1225 if (!empty($announce['comment'])) {
1226 $tags[] = ['type' => 'Mention', 'href' => $announce['actor']['url'], 'name' => '@' . $announce['actor']['addr']];
1233 * Adds attachment data to the JSON document
1235 * @param array $item Data of the item that is to be posted
1236 * @param string $type Object type
1238 * @return array with attachment data
1239 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1241 private static function createAttachmentList($item, $type)
1245 // Currently deactivated, since it creates side effects on Mastodon and Pleroma.
1246 // It will be reactivated, once this cleared.
1248 $attach_data = BBCode::getAttachmentData($item['body']);
1249 if (!empty($attach_data['url'])) {
1250 $attachment = ['type' => 'Page',
1251 'mediaType' => 'text/html',
1252 'url' => $attach_data['url']];
1254 if (!empty($attach_data['title'])) {
1255 $attachment['name'] = $attach_data['title'];
1258 if (!empty($attach_data['description'])) {
1259 $attachment['summary'] = $attach_data['description'];
1262 if (!empty($attach_data['image'])) {
1263 $imgdata = Images::getInfoFromURLCached($attach_data['image']);
1265 $attachment['icon'] = ['type' => 'Image',
1266 'mediaType' => $imgdata['mime'],
1267 'width' => $imgdata[0],
1268 'height' => $imgdata[1],
1269 'url' => $attach_data['image']];
1273 $attachments[] = $attachment;
1276 foreach (Post\Media::getByURIId($item['uri-id'], [Post\Media::DOCUMENT, Post\Media::TORRENT, Post\Media::UNKNOWN]) as $attachment) {
1277 $attachments[] = ['type' => 'Document',
1278 'mediaType' => $attachment['mimetype'],
1279 'url' => $attachment['url'],
1280 'name' => $attachment['description']];
1283 if ($type != 'Note') {
1284 return $attachments;
1287 foreach (Post\Media::getByURIId($item['uri-id'], [Post\Media::AUDIO, Post\Media::IMAGE, Post\Media::VIDEO]) as $attachment) {
1288 $attachments[] = ['type' => 'Document',
1289 'mediaType' => $attachment['mimetype'],
1290 'url' => $attachment['url'],
1291 'name' => $attachment['description']];
1294 return $attachments;
1298 * Callback function to replace a Friendica style mention in a mention that is used on AP
1300 * @param array $match Matching values for the callback
1301 * @return string Replaced mention
1302 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1304 private static function mentionCallback($match)
1306 if (empty($match[1])) {
1310 $data = Contact::getByURL($match[1], false, ['url', 'alias', 'nick']);
1311 if (empty($data['nick'])) {
1315 return '[url=' . ($data['alias'] ?: $data['url']) . ']@' . $data['nick'] . '[/url]';
1319 * Remove image elements since they are added as attachment
1321 * @param string $body
1323 * @return string with removed images
1325 private static function removePictures($body)
1327 // Simplify image codes
1328 $body = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '[img]$3[/img]', $body);
1329 $body = preg_replace("/\[img\=(.*?)\](.*?)\[\/img\]/ism", '[img]$1[/img]', $body);
1331 // Now remove local links
1332 $body = preg_replace_callback(
1333 '/\[url=([^\[\]]*)\]\[img\](.*)\[\/img\]\[\/url\]/Usi',
1335 // We remove the link when it is a link to a local photo page
1336 if (Photo::isLocalPage($match[1])) {
1339 // otherwise we just return the link
1340 return '[url]' . $match[1] . '[/url]';
1345 // Remove all pictures
1346 $body = preg_replace("/\[img\]([^\[\]]*)\[\/img\]/Usi", '', $body);
1352 * Fetches the "context" value for a givem item array from the "conversation" table
1354 * @param array $item
1356 * @return string with context url
1357 * @throws \Exception
1359 private static function fetchContextURLForItem($item)
1361 $conversation = DBA::selectFirst('conversation', ['conversation-href', 'conversation-uri'], ['item-uri' => $item['parent-uri']]);
1362 if (DBA::isResult($conversation) && !empty($conversation['conversation-href'])) {
1363 $context_uri = $conversation['conversation-href'];
1364 } elseif (DBA::isResult($conversation) && !empty($conversation['conversation-uri'])) {
1365 $context_uri = $conversation['conversation-uri'];
1367 $context_uri = $item['parent-uri'] . '#context';
1369 return $context_uri;
1373 * Returns if the post contains sensitive content ("nsfw")
1375 * @param integer $uri_id
1378 * @throws \Exception
1380 private static function isSensitive($uri_id)
1382 return DBA::exists('tag-view', ['uri-id' => $uri_id, 'name' => 'nsfw']);
1386 * Creates event data
1388 * @param array $item
1390 * @return array with the event data
1391 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1393 public static function createEvent($item)
1396 $event['name'] = $item['event-summary'];
1397 $event['content'] = BBCode::convert($item['event-desc'], false, BBCode::ACTIVITYPUB);
1398 $event['startTime'] = DateTimeFormat::utc($item['event-start'] . '+00:00', DateTimeFormat::ATOM);
1400 if (!$item['event-nofinish']) {
1401 $event['endTime'] = DateTimeFormat::utc($item['event-finish'] . '+00:00', DateTimeFormat::ATOM);
1404 if (!empty($item['event-location'])) {
1405 $item['location'] = $item['event-location'];
1406 $event['location'] = self::createLocation($item);
1413 * Creates a note/article object array
1415 * @param array $item
1417 * @return array with the object data
1418 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1419 * @throws \ImagickException
1421 public static function createNote($item)
1427 if ($item['event-type'] == 'event') {
1429 } elseif (!empty($item['title'])) {
1435 if ($item['deleted']) {
1436 $type = 'Tombstone';
1440 $data['id'] = $item['uri'];
1441 $data['type'] = $type;
1443 if ($item['deleted']) {
1447 $data['summary'] = BBCode::toPlaintext(BBCode::getAbstract($item['body'], Protocol::ACTIVITYPUB));
1449 if ($item['uri'] != $item['thr-parent']) {
1450 $data['inReplyTo'] = $item['thr-parent'];
1452 $data['inReplyTo'] = null;
1455 $data['diaspora:guid'] = $item['guid'];
1456 $data['published'] = DateTimeFormat::utc($item['created'] . '+00:00', DateTimeFormat::ATOM);
1458 if ($item['created'] != $item['edited']) {
1459 $data['updated'] = DateTimeFormat::utc($item['edited'] . '+00:00', DateTimeFormat::ATOM);
1462 $data['url'] = $item['plink'];
1463 $data['attributedTo'] = $item['author-link'];
1464 $data['sensitive'] = self::isSensitive($item['uri-id']);
1465 $data['context'] = self::fetchContextURLForItem($item);
1467 if (!empty($item['title'])) {
1468 $data['name'] = BBCode::toPlaintext($item['title'], false);
1471 $permission_block = self::createPermissionBlockForItem($item, false);
1473 $body = $item['body'];
1475 if ($type == 'Note') {
1476 $body = $item['raw-body'] ?? self::removePictures($body);
1477 } elseif (($type == 'Article') && empty($data['summary'])) {
1478 $data['summary'] = BBCode::toPlaintext(Plaintext::shorten(self::removePictures($body), 1000));
1481 if (empty($item['uid']) || !Feature::isEnabled($item['uid'], 'explicit_mentions')) {
1482 $body = self::prependMentions($body, $item['uri-id'], $item['author-link']);
1485 if ($type == 'Event') {
1486 $data = array_merge($data, self::createEvent($item));
1488 $regexp = "/[@!]\[url\=([^\[\]]*)\].*?\[\/url\]/ism";
1489 $body = preg_replace_callback($regexp, ['self', 'mentionCallback'], $body);
1491 $data['content'] = BBCode::convert($body, false, BBCode::ACTIVITYPUB);
1494 // The regular "content" field does contain a minimized HTML. This is done since systems like
1495 // Mastodon has got problems with - for example - embedded pictures.
1496 // The contentMap does contain the unmodified HTML.
1497 $language = self::getLanguage($item);
1498 if (!empty($language)) {
1499 $regexp = "/[@!]\[url\=([^\[\]]*)\].*?\[\/url\]/ism";
1500 $richbody = preg_replace_callback($regexp, ['self', 'mentionCallback'], $item['body']);
1501 $richbody = BBCode::removeAttachment($richbody);
1503 $data['contentMap'][$language] = BBCode::convert($richbody, false);
1506 $data['source'] = ['content' => $item['body'], 'mediaType' => "text/bbcode"];
1508 if (!empty($item['signed_text']) && ($item['uri'] != $item['thr-parent'])) {
1509 $data['diaspora:comment'] = $item['signed_text'];
1512 $data['attachment'] = self::createAttachmentList($item, $type);
1513 $data['tag'] = self::createTagList($item);
1515 if (empty($data['location']) && (!empty($item['coord']) || !empty($item['location']))) {
1516 $data['location'] = self::createLocation($item);
1519 if (!empty($item['app'])) {
1520 $data['generator'] = ['type' => 'Application', 'name' => $item['app']];
1523 $data = array_merge($data, $permission_block);
1529 * Fetches the language from the post, the user or the system.
1531 * @param array $item
1533 * @return string language string
1535 private static function getLanguage(array $item)
1537 // Try to fetch the language from the post itself
1538 if (!empty($item['language'])) {
1539 $languages = array_keys(json_decode($item['language'], true));
1540 if (!empty($languages[0])) {
1541 return $languages[0];
1545 // Otherwise use the user's language
1546 if (!empty($item['uid'])) {
1547 $user = DBA::selectFirst('user', ['language'], ['uid' => $item['uid']]);
1548 if (!empty($user['language'])) {
1549 return $user['language'];
1553 // And finally just use the system language
1554 return DI::config()->get('system', 'language');
1558 * Creates an an "add tag" entry
1560 * @param array $item
1561 * @param array $data activity data
1563 * @return array with activity data for adding tags
1564 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1565 * @throws \ImagickException
1567 private static function createAddTag($item, $data)
1569 $object = XML::parseString($item['object']);
1570 $target = XML::parseString($item["target"]);
1572 $data['diaspora:guid'] = $item['guid'];
1573 $data['actor'] = $item['author-link'];
1574 $data['target'] = (string)$target->id;
1575 $data['summary'] = BBCode::toPlaintext($item['body']);
1576 $data['object'] = ['id' => (string)$object->id, 'type' => 'tag', 'name' => (string)$object->title, 'content' => (string)$object->content];
1582 * Creates an announce object entry
1584 * @param array $item
1585 * @param array $data activity data
1587 * @return array with activity data
1588 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1589 * @throws \ImagickException
1591 private static function createAnnounce($item, $data)
1593 $orig_body = $item['body'];
1594 $announce = self::getAnnounceArray($item);
1595 if (empty($announce)) {
1596 $data['type'] = 'Create';
1597 $data['object'] = self::createNote($item);
1601 if (empty($announce['comment'])) {
1602 // Pure announce, without a quote
1603 $data['type'] = 'Announce';
1604 $data['object'] = $announce['object']['uri'];
1609 $data['type'] = 'Create';
1610 $item['body'] = $announce['comment'] . "\n" . $announce['object']['plink'];
1611 $data['object'] = self::createNote($item);
1613 /// @todo Finally descide how to implement this in AP. This is a possible way:
1614 $data['object']['attachment'][] = self::createNote($announce['object']);
1616 $data['object']['source']['content'] = $orig_body;
1621 * Return announce related data if the item is an annunce
1623 * @param array $item
1627 public static function getAnnounceArray($item)
1629 $reshared = Item::getShareArray($item);
1630 if (empty($reshared['guid'])) {
1634 $reshared_item = Item::selectFirst([], ['guid' => $reshared['guid']]);
1635 if (!DBA::isResult($reshared_item)) {
1639 if (!in_array($reshared_item['network'], [Protocol::ACTIVITYPUB, Protocol::DFRN])) {
1643 $profile = APContact::getByURL($reshared_item['author-link'], false);
1644 if (empty($profile)) {
1648 return ['object' => $reshared_item, 'actor' => $profile, 'comment' => $reshared['comment']];
1652 * Checks if the provided item array is an announce
1654 * @param array $item
1658 public static function isAnnounce($item)
1660 if (!empty($item['verb']) && ($item['verb'] == Activity::ANNOUNCE)) {
1664 $announce = self::getAnnounceArray($item);
1665 if (empty($announce)) {
1669 return empty($announce['comment']);
1673 * Creates an activity id for a given contact id
1675 * @param integer $cid Contact ID of target
1677 * @return bool|string activity id
1679 public static function activityIDFromContact($cid)
1681 $contact = DBA::selectFirst('contact', ['uid', 'id', 'created'], ['id' => $cid]);
1682 if (!DBA::isResult($contact)) {
1686 $hash = hash('ripemd128', $contact['uid'].'-'.$contact['id'].'-'.$contact['created']);
1687 $uuid = substr($hash, 0, 8). '-' . substr($hash, 8, 4) . '-' . substr($hash, 12, 4) . '-' . substr($hash, 16, 4) . '-' . substr($hash, 20, 12);
1688 return DI::baseUrl() . '/activity/' . $uuid;
1692 * Transmits a contact suggestion to a given inbox
1694 * @param integer $uid User ID
1695 * @param string $inbox Target inbox
1696 * @param integer $suggestion_id Suggestion ID
1698 * @return boolean was the transmission successful?
1699 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1701 public static function sendContactSuggestion($uid, $inbox, $suggestion_id)
1703 $owner = User::getOwnerDataById($uid);
1705 $suggestion = DI::fsuggest()->getById($suggestion_id);
1707 $data = ['@context' => ActivityPub::CONTEXT,
1708 'id' => DI::baseUrl() . '/activity/' . System::createGUID(),
1709 'type' => 'Announce',
1710 'actor' => $owner['url'],
1711 'object' => $suggestion->url,
1712 'content' => $suggestion->note,
1713 'instrument' => self::getService(),
1714 'to' => [ActivityPub::PUBLIC_COLLECTION],
1717 $signed = LDSignature::sign($data, $owner);
1719 Logger::log('Deliver profile deletion for user ' . $uid . ' to ' . $inbox . ' via ActivityPub', Logger::DEBUG);
1720 return HTTPSignature::transmit($signed, $inbox, $uid);
1724 * Transmits a profile relocation to a given inbox
1726 * @param integer $uid User ID
1727 * @param string $inbox Target inbox
1729 * @return boolean was the transmission successful?
1730 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1732 public static function sendProfileRelocation($uid, $inbox)
1734 $owner = User::getOwnerDataById($uid);
1736 $data = ['@context' => ActivityPub::CONTEXT,
1737 'id' => DI::baseUrl() . '/activity/' . System::createGUID(),
1738 'type' => 'dfrn:relocate',
1739 'actor' => $owner['url'],
1740 'object' => $owner['url'],
1741 'published' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
1742 'instrument' => self::getService(),
1743 'to' => [ActivityPub::PUBLIC_COLLECTION],
1746 $signed = LDSignature::sign($data, $owner);
1748 Logger::log('Deliver profile relocation for user ' . $uid . ' to ' . $inbox . ' via ActivityPub', Logger::DEBUG);
1749 return HTTPSignature::transmit($signed, $inbox, $uid);
1753 * Transmits a profile deletion to a given inbox
1755 * @param integer $uid User ID
1756 * @param string $inbox Target inbox
1758 * @return boolean was the transmission successful?
1759 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1761 public static function sendProfileDeletion($uid, $inbox)
1763 $owner = User::getOwnerDataById($uid);
1765 if (empty($owner)) {
1766 Logger::error('No owner data found, the deletion message cannot be processed.', ['user' => $uid]);
1770 if (empty($owner['uprvkey'])) {
1771 Logger::error('No private key for owner found, the deletion message cannot be processed.', ['user' => $uid]);
1775 $data = ['@context' => ActivityPub::CONTEXT,
1776 'id' => DI::baseUrl() . '/activity/' . System::createGUID(),
1778 'actor' => $owner['url'],
1779 'object' => $owner['url'],
1780 'published' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
1781 'instrument' => self::getService(),
1782 'to' => [ActivityPub::PUBLIC_COLLECTION],
1785 $signed = LDSignature::sign($data, $owner);
1787 Logger::log('Deliver profile deletion for user ' . $uid . ' to ' . $inbox . ' via ActivityPub', Logger::DEBUG);
1788 return HTTPSignature::transmit($signed, $inbox, $uid);
1792 * Transmits a profile change to a given inbox
1794 * @param integer $uid User ID
1795 * @param string $inbox Target inbox
1797 * @return boolean was the transmission successful?
1798 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1799 * @throws \ImagickException
1801 public static function sendProfileUpdate($uid, $inbox)
1803 $owner = User::getOwnerDataById($uid);
1804 $profile = APContact::getByURL($owner['url']);
1806 $data = ['@context' => ActivityPub::CONTEXT,
1807 'id' => DI::baseUrl() . '/activity/' . System::createGUID(),
1809 'actor' => $owner['url'],
1810 'object' => self::getProfile($uid),
1811 'published' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
1812 'instrument' => self::getService(),
1813 'to' => [$profile['followers']],
1816 $signed = LDSignature::sign($data, $owner);
1818 Logger::log('Deliver profile update for user ' . $uid . ' to ' . $inbox . ' via ActivityPub', Logger::DEBUG);
1819 return HTTPSignature::transmit($signed, $inbox, $uid);
1823 * Transmits a given activity to a target
1825 * @param string $activity Type name
1826 * @param string $target Target profile
1827 * @param integer $uid User ID
1829 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1830 * @throws \ImagickException
1831 * @throws \Exception
1833 public static function sendActivity($activity, $target, $uid, $id = '')
1835 $profile = APContact::getByURL($target);
1836 if (empty($profile['inbox'])) {
1837 Logger::warning('No inbox found for target', ['target' => $target, 'profile' => $profile]);
1841 $owner = User::getOwnerDataById($uid);
1844 $id = DI::baseUrl() . '/activity/' . System::createGUID();
1847 $data = ['@context' => ActivityPub::CONTEXT,
1849 'type' => $activity,
1850 'actor' => $owner['url'],
1851 'object' => $profile['url'],
1852 'instrument' => self::getService(),
1853 'to' => [$profile['url']]];
1855 Logger::log('Sending activity ' . $activity . ' to ' . $target . ' for user ' . $uid, Logger::DEBUG);
1857 $signed = LDSignature::sign($data, $owner);
1858 return HTTPSignature::transmit($signed, $profile['inbox'], $uid);
1862 * Transmits a "follow object" activity to a target
1863 * This is a preparation for sending automated "follow" requests when receiving "Announce" messages
1865 * @param string $object Object URL
1866 * @param string $target Target profile
1867 * @param integer $uid User ID
1869 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1870 * @throws \ImagickException
1871 * @throws \Exception
1873 public static function sendFollowObject($object, $target, $uid = 0)
1875 $profile = APContact::getByURL($target);
1876 if (empty($profile['inbox'])) {
1877 Logger::warning('No inbox found for target', ['target' => $target, 'profile' => $profile]);
1882 // Fetch the list of administrators
1883 $admin_mail = explode(',', str_replace(' ', '', DI::config()->get('config', 'admin_email')));
1885 // We need to use some user as a sender. It doesn't care who it will send. We will use an administrator account.
1886 $condition = ['verified' => true, 'blocked' => false, 'account_removed' => false, 'account_expired' => false, 'email' => $admin_mail];
1887 $first_user = DBA::selectFirst('user', ['uid'], $condition);
1888 $uid = $first_user['uid'];
1891 $condition = ['verb' => Activity::FOLLOW, 'uid' => 0, 'parent-uri' => $object,
1892 'author-id' => Contact::getPublicIdByUserId($uid)];
1893 if (Item::exists($condition)) {
1894 Logger::log('Follow for ' . $object . ' for user ' . $uid . ' does already exist.', Logger::DEBUG);
1898 $owner = User::getOwnerDataById($uid);
1900 $data = ['@context' => ActivityPub::CONTEXT,
1901 'id' => DI::baseUrl() . '/activity/' . System::createGUID(),
1903 'actor' => $owner['url'],
1904 'object' => $object,
1905 'instrument' => self::getService(),
1906 'to' => [$profile['url']]];
1908 Logger::log('Sending follow ' . $object . ' to ' . $target . ' for user ' . $uid, Logger::DEBUG);
1910 $signed = LDSignature::sign($data, $owner);
1911 return HTTPSignature::transmit($signed, $profile['inbox'], $uid);
1915 * Transmit a message that the contact request had been accepted
1917 * @param string $target Target profile
1919 * @param integer $uid User ID
1920 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1921 * @throws \ImagickException
1923 public static function sendContactAccept($target, $id, $uid)
1925 $profile = APContact::getByURL($target);
1926 if (empty($profile['inbox'])) {
1927 Logger::warning('No inbox found for target', ['target' => $target, 'profile' => $profile]);
1931 $owner = User::getOwnerDataById($uid);
1932 $data = ['@context' => ActivityPub::CONTEXT,
1933 'id' => DI::baseUrl() . '/activity/' . System::createGUID(),
1935 'actor' => $owner['url'],
1937 'id' => (string)$id,
1939 'actor' => $profile['url'],
1940 'object' => $owner['url']
1942 'instrument' => self::getService(),
1943 'to' => [$profile['url']]];
1945 Logger::debug('Sending accept to ' . $target . ' for user ' . $uid . ' with id ' . $id);
1947 $signed = LDSignature::sign($data, $owner);
1948 HTTPSignature::transmit($signed, $profile['inbox'], $uid);
1952 * Reject a contact request or terminates the contact relation
1954 * @param string $target Target profile
1956 * @param integer $uid User ID
1957 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1958 * @throws \ImagickException
1960 public static function sendContactReject($target, $id, $uid)
1962 $profile = APContact::getByURL($target);
1963 if (empty($profile['inbox'])) {
1964 Logger::warning('No inbox found for target', ['target' => $target, 'profile' => $profile]);
1968 $owner = User::getOwnerDataById($uid);
1969 $data = ['@context' => ActivityPub::CONTEXT,
1970 'id' => DI::baseUrl() . '/activity/' . System::createGUID(),
1972 'actor' => $owner['url'],
1974 'id' => (string)$id,
1976 'actor' => $profile['url'],
1977 'object' => $owner['url']
1979 'instrument' => self::getService(),
1980 'to' => [$profile['url']]];
1982 Logger::debug('Sending reject to ' . $target . ' for user ' . $uid . ' with id ' . $id);
1984 $signed = LDSignature::sign($data, $owner);
1985 HTTPSignature::transmit($signed, $profile['inbox'], $uid);
1989 * Transmits a message that we don't want to follow this contact anymore
1991 * @param string $target Target profile
1992 * @param integer $uid User ID
1993 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1994 * @throws \ImagickException
1995 * @throws \Exception
1996 * @return bool success
1998 public static function sendContactUndo($target, $cid, $uid)
2000 $profile = APContact::getByURL($target);
2001 if (empty($profile['inbox'])) {
2002 Logger::warning('No inbox found for target', ['target' => $target, 'profile' => $profile]);
2006 $object_id = self::activityIDFromContact($cid);
2007 if (empty($object_id)) {
2011 $id = DI::baseUrl() . '/activity/' . System::createGUID();
2013 $owner = User::getOwnerDataById($uid);
2014 $data = ['@context' => ActivityPub::CONTEXT,
2017 'actor' => $owner['url'],
2018 'object' => ['id' => $object_id, 'type' => 'Follow',
2019 'actor' => $owner['url'],
2020 'object' => $profile['url']],
2021 'instrument' => self::getService(),
2022 'to' => [$profile['url']]];
2024 Logger::log('Sending undo to ' . $target . ' for user ' . $uid . ' with id ' . $id, Logger::DEBUG);
2026 $signed = LDSignature::sign($data, $owner);
2027 return HTTPSignature::transmit($signed, $profile['inbox'], $uid);
2030 private static function prependMentions($body, int $uriid, string $authorLink)
2034 foreach (Tag::getByURIId($uriid, [Tag::IMPLICIT_MENTION]) as $tag) {
2035 $profile = Contact::getByURL($tag['url'], false, ['addr', 'contact-type', 'nick']);
2036 if (!empty($profile['addr'])
2037 && $profile['contact-type'] != Contact::TYPE_COMMUNITY
2038 && !strstr($body, $profile['addr'])
2039 && !strstr($body, $tag['url'])
2040 && $tag['url'] !== $authorLink
2042 $mentions[] = '@[url=' . $tag['url'] . ']' . $profile['nick'] . '[/url]';
2046 $mentions[] = $body;
2048 return implode(' ', $mentions);