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\Tag;
41 use Friendica\Model\User;
42 use Friendica\Protocol\Activity;
43 use Friendica\Protocol\ActivityPub;
44 use Friendica\Util\DateTimeFormat;
45 use Friendica\Util\HTTPSignature;
46 use Friendica\Util\Images;
47 use Friendica\Util\JsonLD;
48 use Friendica\Util\LDSignature;
49 use Friendica\Util\Map;
50 use Friendica\Util\Network;
51 use Friendica\Util\XML;
53 require_once 'include/api.php';
54 require_once 'mod/share.php';
57 * ActivityPub Transmitter Protocol class
65 * Collects a list of contacts of the given owner
67 * @param array $owner Owner array
68 * @param int|array $rel The relevant value(s) contact.rel should match
69 * @param string $module The name of the relevant AP endpoint module (followers|following)
70 * @param integer $page Page number
72 * @return array of owners
75 public static function getContacts($owner, $rel, $module, $page = null)
79 'uid' => $owner['uid'],
86 $condition = DBA::buildCondition($parameters);
88 $sql = "SELECT COUNT(*) as `count`
90 JOIN `apcontact` ON `apcontact`.`url` = `contact`.`url`
93 $contacts = DBA::fetchFirst($sql, ...$parameters);
95 $modulePath = '/' . $module . '/';
97 $data = ['@context' => ActivityPub::CONTEXT];
98 $data['id'] = DI::baseUrl() . $modulePath . $owner['nickname'];
99 $data['type'] = 'OrderedCollection';
100 $data['totalItems'] = $contacts['count'];
102 // When we hide our friends we will only show the pure number but don't allow more.
103 $profile = Profile::getByUID($owner['uid']);
104 if (!empty($profile['hide-friends'])) {
109 $data['first'] = DI::baseUrl() . $modulePath . $owner['nickname'] . '?page=1';
111 $data['type'] = 'OrderedCollectionPage';
114 $sql = "SELECT `contact`.`url`
116 JOIN `apcontact` ON `apcontact`.`url` = `contact`.`url`
120 $parameters[] = ($page - 1) * 100;
123 $contacts = DBA::p($sql, ...$parameters);
124 while ($contact = DBA::fetch($contacts)) {
125 $list[] = $contact['url'];
127 DBA::close($contacts);
130 $data['next'] = DI::baseUrl() . $modulePath . $owner['nickname'] . '?page=' . ($page + 1);
133 $data['partOf'] = DI::baseUrl() . $modulePath . $owner['nickname'];
135 $data['orderedItems'] = $list;
142 * Public posts for the given owner
144 * @param array $owner Owner array
145 * @param integer $page Page number
146 * @param string $requester URL of requesting account
148 * @return array of posts
149 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
150 * @throws \ImagickException
152 public static function getOutbox($owner, $page = null, $requester = '')
154 $public_contact = Contact::getIdForURL($owner['url']);
155 $condition = ['uid' => 0, 'contact-id' => $public_contact,
156 'private' => [Item::PUBLIC, Item::UNLISTED]];
158 if (!empty($requester)) {
159 $requester_id = Contact::getIdForURL($requester, $owner['uid']);
160 if (!empty($requester_id)) {
161 $permissionSets = DI::permissionSet()->selectByContactId($requester_id, $owner['uid']);
162 if (!empty($permissionSets)) {
163 $condition = ['uid' => $owner['uid'], 'origin' => true,
164 'psid' => array_merge($permissionSets->column('id'),
165 [DI::permissionSet()->getIdFromACL($owner['uid'], '', '', '', '')])];
170 $condition = array_merge($condition,
171 ['author-id' => $public_contact,
172 'gravity' => [GRAVITY_PARENT, GRAVITY_COMMENT],
173 'deleted' => false, 'visible' => true, 'moderated' => false]);
175 $count = DBA::count('item', $condition);
177 $data = ['@context' => ActivityPub::CONTEXT];
178 $data['id'] = DI::baseUrl() . '/outbox/' . $owner['nickname'];
179 $data['type'] = 'OrderedCollection';
180 $data['totalItems'] = $count;
183 $data['first'] = DI::baseUrl() . '/outbox/' . $owner['nickname'] . '?page=1';
185 $data['type'] = 'OrderedCollectionPage';
188 $condition['parent-network'] = Protocol::NATIVE_SUPPORT;
190 $items = Item::select(['id'], $condition, ['limit' => [($page - 1) * 20, 20], 'order' => ['created' => true]]);
191 while ($item = Item::fetch($items)) {
192 $activity = self::createActivityFromItem($item['id'], true);
193 $activity['type'] = $activity['type'] == 'Update' ? 'Create' : $activity['type'];
195 // Only list "Create" activity objects here, no reshares
196 if (!empty($activity['object']) && ($activity['type'] == 'Create')) {
197 $list[] = $activity['object'];
202 $data['next'] = DI::baseUrl() . '/outbox/' . $owner['nickname'] . '?page=' . ($page + 1);
205 $data['partOf'] = DI::baseUrl() . '/outbox/' . $owner['nickname'];
207 $data['orderedItems'] = $list;
214 * Return the service array containing information the used software and it's url
216 * @return array with service data
218 private static function getService()
220 return ['type' => 'Service',
221 'name' => FRIENDICA_PLATFORM . " '" . FRIENDICA_CODENAME . "' " . FRIENDICA_VERSION . '-' . DB_UPDATE_VERSION,
222 'url' => DI::baseUrl()->get()];
226 * Return the ActivityPub profile of the given user
228 * @param integer $uid User ID
229 * @return array with profile data
230 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
232 public static function getProfile($uid)
235 $condition = ['uid' => $uid, 'blocked' => false, 'account_expired' => false,
236 'account_removed' => false, 'verified' => true];
237 $fields = ['guid', 'nickname', 'pubkey', 'account-type', 'page-flags'];
238 $user = DBA::selectFirst('user', $fields, $condition);
239 if (!DBA::isResult($user)) {
243 $fields = ['locality', 'region', 'country-name'];
244 $profile = DBA::selectFirst('profile', $fields, ['uid' => $uid]);
245 if (!DBA::isResult($profile)) {
249 $fields = ['name', 'url', 'location', 'about', 'avatar', 'photo'];
250 $contact = DBA::selectFirst('contact', $fields, ['uid' => $uid, 'self' => true]);
251 if (!DBA::isResult($contact)) {
255 $contact = User::getSystemAccount();
256 $user = ['guid' => '', 'nickname' => $contact['nick'], 'pubkey' => $contact['pubkey'],
257 'account-type' => $contact['contact-type'], 'page-flags' => User::PAGE_FLAGS_NORMAL];
258 $profile = ['locality' => '', 'region' => '', 'country-name' => ''];
261 $data = ['@context' => ActivityPub::CONTEXT];
262 $data['id'] = $contact['url'];
264 if (!empty($user['guid'])) {
265 $data['diaspora:guid'] = $user['guid'];
268 $data['type'] = ActivityPub::ACCOUNT_TYPES[$user['account-type']];
271 $data['following'] = DI::baseUrl() . '/following/' . $user['nickname'];
272 $data['followers'] = DI::baseUrl() . '/followers/' . $user['nickname'];
273 $data['inbox'] = DI::baseUrl() . '/inbox/' . $user['nickname'];
274 $data['outbox'] = DI::baseUrl() . '/outbox/' . $user['nickname'];
276 $data['inbox'] = DI::baseUrl() . '/friendica/inbox';
279 $data['preferredUsername'] = $user['nickname'];
280 $data['name'] = $contact['name'];
282 if (!empty($profile['country-name'] . $profile['region'] . $profile['locality'])) {
283 $data['vcard:hasAddress'] = ['@type' => 'vcard:Home', 'vcard:country-name' => $profile['country-name'],
284 'vcard:region' => $profile['region'], 'vcard:locality' => $profile['locality']];
287 if (!empty($contact['about'])) {
288 $data['summary'] = BBCode::convert($contact['about'], false);
291 $data['url'] = $contact['url'];
292 $data['manuallyApprovesFollowers'] = in_array($user['page-flags'], [User::PAGE_FLAGS_NORMAL, User::PAGE_FLAGS_PRVGROUP]);
293 $data['publicKey'] = ['id' => $contact['url'] . '#main-key',
294 'owner' => $contact['url'],
295 'publicKeyPem' => $user['pubkey']];
296 $data['endpoints'] = ['sharedInbox' => DI::baseUrl() . '/inbox'];
297 $data['icon'] = ['type' => 'Image',
298 'url' => $contact['photo']];
300 $data['generator'] = self::getService();
302 // tags: https://kitty.town/@inmysocks/100656097926961126.json
307 * @param string $username
309 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
311 public static function getDeletedUser($username)
314 '@context' => ActivityPub::CONTEXT,
315 'id' => DI::baseUrl() . '/profile/' . $username,
316 'type' => 'Tombstone',
317 'published' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
318 'updated' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
319 'deleted' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
324 * Returns an array with permissions of a given item array
328 * @return array with permissions
329 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
330 * @throws \ImagickException
332 private static function fetchPermissionBlockFromConversation($item)
334 if (empty($item['thr-parent'])) {
338 $condition = ['item-uri' => $item['thr-parent'], 'protocol' => Conversation::PARCEL_ACTIVITYPUB];
339 $conversation = DBA::selectFirst('conversation', ['source'], $condition);
340 if (!DBA::isResult($conversation)) {
344 $activity = json_decode($conversation['source'], true);
346 $actor = JsonLD::fetchElement($activity, 'actor', 'id');
347 $profile = APContact::getByURL($actor);
349 $item_profile = APContact::getByURL($item['author-link']);
350 $exclude[] = $item['author-link'];
352 if ($item['gravity'] == GRAVITY_PARENT) {
353 $exclude[] = $item['owner-link'];
356 $permissions['to'][] = $actor;
358 foreach (['to', 'cc', 'bto', 'bcc'] as $element) {
359 if (empty($activity[$element])) {
362 if (is_string($activity[$element])) {
363 $activity[$element] = [$activity[$element]];
366 foreach ($activity[$element] as $receiver) {
367 if (empty($receiver)) {
371 if (!empty($profile['followers']) && $receiver == $profile['followers'] && !empty($item_profile['followers'])) {
372 $permissions[$element][] = $item_profile['followers'];
373 } elseif (!in_array($receiver, $exclude)) {
374 $permissions[$element][] = $receiver;
382 * Creates an array of permissions from an item thread
384 * @param array $item Item array
385 * @param boolean $blindcopy addressing via "bcc" or "cc"?
386 * @param integer $last_id Last item id for adding receivers
387 * @param boolean $forum_mode "true" means that we are sending content to a forum
389 * @return array with permission data
390 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
391 * @throws \ImagickException
393 private static function createPermissionBlockForItem($item, $blindcopy, $last_id = 0, $forum_mode = false)
396 $last_id = $item['id'];
402 // Check if we should always deliver our stuff via BCC
403 if (!empty($item['uid'])) {
404 $profile = User::getOwnerDataById($item['uid']);
405 if (!empty($profile)) {
406 $always_bcc = $profile['hide-friends'];
407 $isforum = $profile['account-type'] == User::ACCOUNT_TYPE_COMMUNITY;
411 if (DI::config()->get('system', 'ap_always_bcc')) {
415 if ((self::isAnnounce($item) && !$isforum) || DI::config()->get('debug', 'total_ap_delivery')) {
416 // Will be activated in a later step
417 $networks = Protocol::FEDERATED;
419 // For now only send to these contacts:
420 $networks = [Protocol::ACTIVITYPUB, Protocol::OSTATUS];
423 $data = ['to' => [], 'cc' => [], 'bcc' => []];
425 if ($item['gravity'] == GRAVITY_PARENT) {
426 $actor_profile = APContact::getByURL($item['owner-link']);
428 $actor_profile = APContact::getByURL($item['author-link']);
431 $terms = Tag::getByURIId($item['uri-id'], [Tag::MENTION, Tag::IMPLICIT_MENTION, Tag::EXCLUSIVE_MENTION]);
433 if ($item['private'] != Item::PRIVATE) {
434 // Directly mention the original author upon a quoted reshare.
435 // Else just ensure that the original author receives the reshare.
436 $announce = self::getAnnounceArray($item);
437 if (!empty($announce['comment'])) {
438 $data['to'][] = $announce['actor']['url'];
439 } elseif (!empty($announce)) {
440 $data['cc'][] = $announce['actor']['url'];
443 $data = array_merge($data, self::fetchPermissionBlockFromConversation($item));
445 // Check if the item is completely public or unlisted
446 if ($item['private'] == Item::PUBLIC) {
447 $data['to'][] = ActivityPub::PUBLIC_COLLECTION;
449 $data['cc'][] = ActivityPub::PUBLIC_COLLECTION;
452 foreach ($terms as $term) {
453 $profile = APContact::getByURL($term['url'], false);
454 if (!empty($profile)) {
455 $data['to'][] = $profile['url'];
459 $receiver_list = Item::enumeratePermissions($item, true);
461 foreach ($terms as $term) {
462 $cid = Contact::getIdForURL($term['url'], $item['uid']);
463 if (!empty($cid) && in_array($cid, $receiver_list)) {
464 $contact = DBA::selectFirst('contact', ['url', 'network', 'protocol'], ['id' => $cid]);
465 if (!DBA::isResult($contact) || (!in_array($contact['network'], $networks) && ($contact['protocol'] != Protocol::ACTIVITYPUB))) {
469 if ($isforum && DBA::isResult($contact) && ($contact['dfrn'] == Protocol::DFRN)) {
473 if (!empty($profile = APContact::getByURL($contact['url'], false))) {
474 $data['to'][] = $profile['url'];
479 foreach ($receiver_list as $receiver) {
480 $contact = DBA::selectFirst('contact', ['url', 'hidden', 'network', 'protocol'], ['id' => $receiver]);
481 if (!DBA::isResult($contact) || (!in_array($contact['network'], $networks) && ($contact['protocol'] != Protocol::ACTIVITYPUB))) {
485 if ($isforum && DBA::isResult($contact) && ($contact['dfrn'] == Protocol::DFRN)) {
489 if (!empty($profile = APContact::getByURL($contact['url'], false))) {
490 if ($contact['hidden'] || $always_bcc) {
491 $data['bcc'][] = $profile['url'];
493 $data['cc'][] = $profile['url'];
499 if (!empty($item['parent'])) {
500 $parents = Item::select(['id', 'author-link', 'owner-link', 'gravity', 'uri'], ['parent' => $item['parent']]);
501 while ($parent = Item::fetch($parents)) {
502 if ($parent['gravity'] == GRAVITY_PARENT) {
503 $profile = APContact::getByURL($parent['owner-link'], false);
504 if (!empty($profile)) {
505 if ($item['gravity'] != GRAVITY_PARENT) {
506 // Comments to forums are directed to the forum
507 // But comments to forums aren't directed to the followers collection
508 // This rule is only valid when the actor isn't the forum.
509 // The forum needs to transmit their content to their followers.
510 if (($profile['type'] == 'Group') && ($profile['url'] != $actor_profile['url'])) {
511 $data['to'][] = $profile['url'];
513 $data['cc'][] = $profile['url'];
514 if (($item['private'] != Item::PRIVATE) && !empty($actor_profile['followers'])) {
515 $data['cc'][] = $actor_profile['followers'];
519 // Public thread parent post always are directed to the followers
520 if (($item['private'] != Item::PRIVATE) && !$forum_mode) {
521 $data['cc'][] = $actor_profile['followers'];
527 // Don't include data from future posts
528 if ($parent['id'] >= $last_id) {
532 $profile = APContact::getByURL($parent['author-link'], false);
533 if (!empty($profile)) {
534 if (($profile['type'] == 'Group') || ($parent['uri'] == $item['thr-parent'])) {
535 $data['to'][] = $profile['url'];
537 $data['cc'][] = $profile['url'];
541 DBA::close($parents);
544 $data['to'] = array_unique($data['to']);
545 $data['cc'] = array_unique($data['cc']);
546 $data['bcc'] = array_unique($data['bcc']);
548 if (($key = array_search($item['author-link'], $data['to'])) !== false) {
549 unset($data['to'][$key]);
552 if (($key = array_search($item['author-link'], $data['cc'])) !== false) {
553 unset($data['cc'][$key]);
556 if (($key = array_search($item['author-link'], $data['bcc'])) !== false) {
557 unset($data['bcc'][$key]);
560 foreach ($data['to'] as $to) {
561 if (($key = array_search($to, $data['cc'])) !== false) {
562 unset($data['cc'][$key]);
565 if (($key = array_search($to, $data['bcc'])) !== false) {
566 unset($data['bcc'][$key]);
570 foreach ($data['cc'] as $cc) {
571 if (($key = array_search($cc, $data['bcc'])) !== false) {
572 unset($data['bcc'][$key]);
576 $receivers = ['to' => array_values($data['to']), 'cc' => array_values($data['cc']), 'bcc' => array_values($data['bcc'])];
579 unset($receivers['bcc']);
586 * Check if an inbox is archived
588 * @param string $url Inbox url
590 * @return boolean "true" if inbox is archived
592 private static function archivedInbox($url)
594 return DBA::exists('inbox-status', ['url' => $url, 'archive' => true]);
598 * Fetches a list of inboxes of followers of a given user
600 * @param integer $uid User ID
601 * @param boolean $personal fetch personal inboxes
603 * @return array of follower inboxes
604 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
605 * @throws \ImagickException
607 public static function fetchTargetInboxesforUser($uid, $personal = false)
613 if (!empty($item['uid'])) {
614 $profile = User::getOwnerDataById($item['uid']);
615 if (!empty($profile)) {
616 $isforum = $profile['account-type'] == User::ACCOUNT_TYPE_COMMUNITY;
620 if (DI::config()->get('debug', 'total_ap_delivery')) {
621 // Will be activated in a later step
622 $networks = Protocol::FEDERATED;
624 // For now only send to these contacts:
625 $networks = [Protocol::ACTIVITYPUB, Protocol::OSTATUS];
628 $condition = ['uid' => $uid, 'archive' => false, 'pending' => false];
631 $condition['rel'] = [Contact::FOLLOWER, Contact::FRIEND];
634 $contacts = DBA::select('contact', ['url', 'network', 'protocol'], $condition);
635 while ($contact = DBA::fetch($contacts)) {
636 if (Contact::isLocal($contact['url'])) {
640 if (!in_array($contact['network'], $networks) && ($contact['protocol'] != Protocol::ACTIVITYPUB)) {
644 if ($isforum && ($contact['dfrn'] == Protocol::DFRN)) {
648 if (Network::isUrlBlocked($contact['url'])) {
652 $profile = APContact::getByURL($contact['url'], false);
653 if (!empty($profile)) {
654 if (empty($profile['sharedinbox']) || $personal) {
655 $target = $profile['inbox'];
657 $target = $profile['sharedinbox'];
659 if (!self::archivedInbox($target)) {
660 $inboxes[$target] = $target;
664 DBA::close($contacts);
670 * Fetches an array of inboxes for the given item and user
672 * @param array $item Item array
673 * @param integer $uid User ID
674 * @param boolean $personal fetch personal inboxes
675 * @param integer $last_id Last item id for adding receivers
676 * @param boolean $forum_mode "true" means that we are sending content to a forum
677 * @return array with inboxes
678 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
679 * @throws \ImagickException
681 public static function fetchTargetInboxes($item, $uid, $personal = false, $last_id = 0, $forum_mode = false)
683 $permissions = self::createPermissionBlockForItem($item, true, $last_id, $forum_mode);
684 if (empty($permissions)) {
690 if ($item['gravity'] == GRAVITY_ACTIVITY) {
691 $item_profile = APContact::getByURL($item['author-link'], false);
693 $item_profile = APContact::getByURL($item['owner-link'], false);
696 if (empty($item_profile)) {
700 $profile_uid = User::getIdForURL($item_profile['url']);
702 foreach (['to', 'cc', 'bto', 'bcc'] as $element) {
703 if (empty($permissions[$element])) {
707 $blindcopy = in_array($element, ['bto', 'bcc']);
709 foreach ($permissions[$element] as $receiver) {
710 if (empty($receiver) || Network::isUrlBlocked($receiver)) {
714 if ($item_profile && ($receiver == $item_profile['followers']) && ($uid == $profile_uid)) {
715 $inboxes = array_merge($inboxes, self::fetchTargetInboxesforUser($uid, $personal));
717 if (Contact::isLocal($receiver)) {
721 $profile = APContact::getByURL($receiver, false);
722 if (!empty($profile)) {
723 if (empty($profile['sharedinbox']) || $personal || $blindcopy) {
724 $target = $profile['inbox'];
726 $target = $profile['sharedinbox'];
728 if (!self::archivedInbox($target)) {
729 $inboxes[$target] = $target;
740 * Creates an array in the structure of the item table for a given mail id
742 * @param integer $mail_id
747 public static function ItemArrayFromMail($mail_id)
749 $mail = DBA::selectFirst('mail', [], ['id' => $mail_id]);
750 if (!DBA::isResult($mail)) {
754 $mail['uri-id'] = ItemURI::insert(['uri' => $mail['uri'], 'guid' => $mail['guid']]);
756 $reply = DBA::selectFirst('mail', ['uri'], ['parent-uri' => $mail['parent-uri'], 'reply' => false]);
758 // Making the post more compatible for Mastodon by:
759 // - Making it a note and not an article (no title)
760 // - Moving the title into the "summary" field that is used as a "content warning"
761 $mail['body'] = '[abstract]' . $mail['title'] . "[/abstract]\n" . $mail['body'];
764 $mail['author-link'] = $mail['owner-link'] = $mail['from-url'];
765 $mail['allow_cid'] = '<'.$mail['contact-id'].'>';
766 $mail['allow_gid'] = '';
767 $mail['deny_cid'] = '';
768 $mail['deny_gid'] = '';
769 $mail['private'] = true;
770 $mail['deleted'] = false;
771 $mail['edited'] = $mail['created'];
772 $mail['plink'] = $mail['uri'];
773 $mail['thr-parent'] = $reply['uri'];
774 $mail['gravity'] = ($mail['reply'] ? GRAVITY_COMMENT: GRAVITY_PARENT);
776 $mail['event-type'] = '';
777 $mail['attach'] = '';
785 * Creates an activity array for a given mail id
787 * @param integer $mail_id
788 * @param boolean $object_mode Is the activity item is used inside another object?
790 * @return array of activity
793 public static function createActivityFromMail($mail_id, $object_mode = false)
795 $mail = self::ItemArrayFromMail($mail_id);
796 $object = self::createNote($mail);
799 $data = ['@context' => ActivityPub::CONTEXT];
804 $data['id'] = $mail['uri'] . '/Create';
805 $data['type'] = 'Create';
806 $data['actor'] = $mail['author-link'];
807 $data['published'] = DateTimeFormat::utc($mail['created'] . '+00:00', DateTimeFormat::ATOM);
808 $data['instrument'] = self::getService();
809 $data = array_merge($data, self::createPermissionBlockForItem($mail, true));
811 if (empty($data['to']) && !empty($data['cc'])) {
812 $data['to'] = $data['cc'];
815 if (empty($data['to']) && !empty($data['bcc'])) {
816 $data['to'] = $data['bcc'];
822 $object['to'] = $data['to'];
823 $object['tag'] = [['type' => 'Mention', 'href' => $object['to'][0], 'name' => '']];
825 unset($object['cc']);
826 unset($object['bcc']);
828 $data['directMessage'] = true;
830 $data['object'] = $object;
832 $owner = User::getOwnerDataById($mail['uid']);
834 if (!$object_mode && !empty($owner)) {
835 return LDSignature::sign($data, $owner);
842 * Returns the activity type of a given item
846 * @return string with activity type
847 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
848 * @throws \ImagickException
850 private static function getTypeOfItem($item)
854 // Only check for a reshare, if it is a real reshare and no quoted reshare
855 if (strpos($item['body'], "[share") === 0) {
856 $announce = self::getAnnounceArray($item);
857 $reshared = !empty($announce);
862 } elseif ($item['verb'] == Activity::POST) {
863 if ($item['created'] == $item['edited']) {
868 } elseif ($item['verb'] == Activity::LIKE) {
870 } elseif ($item['verb'] == Activity::DISLIKE) {
872 } elseif ($item['verb'] == Activity::ATTEND) {
874 } elseif ($item['verb'] == Activity::ATTENDNO) {
876 } elseif ($item['verb'] == Activity::ATTENDMAYBE) {
877 $type = 'TentativeAccept';
878 } elseif ($item['verb'] == Activity::FOLLOW) {
880 } elseif ($item['verb'] == Activity::TAG) {
882 } elseif ($item['verb'] == Activity::ANNOUNCE) {
892 * Creates the activity or fetches it from the cache
894 * @param integer $item_id
895 * @param boolean $force Force new cache entry
897 * @return array with the activity
900 public static function createCachedActivityFromItem($item_id, $force = false)
902 $cachekey = 'APDelivery:createActivity:' . $item_id;
905 $data = DI::cache()->get($cachekey);
906 if (!is_null($data)) {
911 $data = self::createActivityFromItem($item_id);
913 DI::cache()->set($cachekey, $data, Duration::QUARTER_HOUR);
918 * Creates an activity array for a given item id
920 * @param integer $item_id
921 * @param boolean $object_mode Is the activity item is used inside another object?
923 * @return array of activity
926 public static function createActivityFromItem($item_id, $object_mode = false)
928 Logger::info('Fetching activity', ['item' => $item_id]);
929 $item = Item::selectFirst([], ['id' => $item_id, 'parent-network' => Protocol::NATIVE_SUPPORT]);
930 if (!DBA::isResult($item)) {
934 // In case of a forum post ensure to return the original post if author and forum are on the same machine
935 if (!empty($item['forum_mode'])) {
936 $author = Contact::getById($item['author-id'], ['nurl']);
937 if (!empty($author['nurl'])) {
938 $self = Contact::selectFirst(['uid'], ['nurl' => $author['nurl'], 'self' => true]);
939 if (!empty($self['uid'])) {
940 $item = Item::selectFirst([], ['uri-id' => $item['uri-id'], 'uid' => $self['uid']]);
946 $condition = ['item-uri' => $item['uri'], 'protocol' => Conversation::PARCEL_ACTIVITYPUB];
947 $conversation = DBA::selectFirst('conversation', ['source'], $condition);
948 if (DBA::isResult($conversation)) {
949 $data = json_decode($conversation['source'], true);
950 if (!empty($data['type'])) {
951 if (in_array($data['type'], ['Create', 'Update'])) {
953 unset($data['@context']);
954 unset($data['signature']);
956 Logger::info('Return stored conversation', ['item' => $item_id]);
958 } elseif (in_array('as:' . $data['type'], Receiver::CONTENT_TYPES)) {
959 if (!empty($data['@context'])) {
960 $context = $data['@context'];
961 unset($data['@context']);
963 unset($data['actor']);
969 $type = self::getTypeOfItem($item);
973 $data = ['@context' => $context ?? ActivityPub::CONTEXT];
975 if ($item['deleted'] && ($item['gravity'] == GRAVITY_ACTIVITY)) {
977 } elseif ($item['deleted']) {
984 if (($item['gravity'] == GRAVITY_ACTIVITY) && ($type != 'Undo')) {
985 $data['id'] = $item['uri'];
987 $data['id'] = $item['uri'] . '/' . $type;
990 $data['type'] = $type;
992 if (($type != 'Announce') || ($item['gravity'] != GRAVITY_PARENT)) {
993 $data['actor'] = $item['author-link'];
995 $data['actor'] = $item['owner-link'];
998 $data['published'] = DateTimeFormat::utc($item['created'] . '+00:00', DateTimeFormat::ATOM);
1000 $data['instrument'] = self::getService();
1002 $data = array_merge($data, self::createPermissionBlockForItem($item, false));
1004 if (in_array($data['type'], ['Create', 'Update', 'Delete'])) {
1005 $data['object'] = $object ?? self::createNote($item);
1006 } elseif ($data['type'] == 'Add') {
1007 $data = self::createAddTag($item, $data);
1008 } elseif ($data['type'] == 'Announce') {
1009 if ($item['verb'] == ACTIVITY::ANNOUNCE) {
1010 $data['object'] = $item['thr-parent'];
1012 $data = self::createAnnounce($item, $data);
1014 } elseif ($data['type'] == 'Follow') {
1015 $data['object'] = $item['parent-uri'];
1016 } elseif ($data['type'] == 'Undo') {
1017 $data['object'] = self::createActivityFromItem($item_id, true);
1019 $data['diaspora:guid'] = $item['guid'];
1020 if (!empty($item['signed_text'])) {
1021 $data['diaspora:like'] = $item['signed_text'];
1023 $data['object'] = $item['thr-parent'];
1026 if (!empty($item['contact-uid'])) {
1027 $uid = $item['contact-uid'];
1029 $uid = $item['uid'];
1032 $owner = User::getOwnerDataById($uid);
1034 Logger::info('Fetched activity', ['item' => $item_id, 'uid' => $uid]);
1036 // We don't sign if we aren't the actor. This is important for relaying content especially for forums
1037 if (!$object_mode && !empty($owner) && ($data['actor'] == $owner['url'])) {
1038 return LDSignature::sign($data, $owner);
1043 /// @todo Create "conversation" entry
1047 * Creates a location entry for a given item array
1049 * @param array $item
1051 * @return array with location array
1053 private static function createLocation($item)
1055 $location = ['type' => 'Place'];
1057 if (!empty($item['location'])) {
1058 $location['name'] = $item['location'];
1063 if (empty($item['coord'])) {
1064 $coord = Map::getCoordinates($item['location']);
1066 $coords = explode(' ', $item['coord']);
1067 if (count($coords) == 2) {
1068 $coord = ['lat' => $coords[0], 'lon' => $coords[1]];
1072 if (!empty($coord['lat']) && !empty($coord['lon'])) {
1073 $location['latitude'] = $coord['lat'];
1074 $location['longitude'] = $coord['lon'];
1081 * Returns a tag array for a given item array
1083 * @param array $item
1085 * @return array of tags
1086 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1088 private static function createTagList($item)
1092 $terms = Tag::getByURIId($item['uri-id'], [Tag::HASHTAG, Tag::MENTION, Tag::IMPLICIT_MENTION, Tag::EXCLUSIVE_MENTION]);
1093 foreach ($terms as $term) {
1094 if ($term['type'] == Tag::HASHTAG) {
1095 $url = DI::baseUrl() . '/search?tag=' . urlencode($term['name']);
1096 $tags[] = ['type' => 'Hashtag', 'href' => $url, 'name' => '#' . $term['name']];
1098 $contact = Contact::getByURL($term['url'], false, ['addr']);
1099 if (empty($contact)) {
1102 if (!empty($contact['addr'])) {
1103 $mention = '@' . $contact['addr'];
1105 $mention = '@' . $term['url'];
1108 $tags[] = ['type' => 'Mention', 'href' => $term['url'], 'name' => $mention];
1112 $announce = self::getAnnounceArray($item);
1113 // Mention the original author upon commented reshares
1114 if (!empty($announce['comment'])) {
1115 $tags[] = ['type' => 'Mention', 'href' => $announce['actor']['url'], 'name' => '@' . $announce['actor']['addr']];
1122 * Adds attachment data to the JSON document
1124 * @param array $item Data of the item that is to be posted
1125 * @param string $type Object type
1127 * @return array with attachment data
1128 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1130 private static function createAttachmentList($item, $type)
1134 // Currently deactivated, since it creates side effects on Mastodon and Pleroma.
1135 // It will be reactivated, once this cleared.
1137 $attach_data = BBCode::getAttachmentData($item['body']);
1138 if (!empty($attach_data['url'])) {
1139 $attachment = ['type' => 'Page',
1140 'mediaType' => 'text/html',
1141 'url' => $attach_data['url']];
1143 if (!empty($attach_data['title'])) {
1144 $attachment['name'] = $attach_data['title'];
1147 if (!empty($attach_data['description'])) {
1148 $attachment['summary'] = $attach_data['description'];
1151 if (!empty($attach_data['image'])) {
1152 $imgdata = Images::getInfoFromURLCached($attach_data['image']);
1154 $attachment['icon'] = ['type' => 'Image',
1155 'mediaType' => $imgdata['mime'],
1156 'width' => $imgdata[0],
1157 'height' => $imgdata[1],
1158 'url' => $attach_data['image']];
1162 $attachments[] = $attachment;
1165 $arr = explode('[/attach],', $item['attach']);
1167 foreach ($arr as $r) {
1169 $cnt = preg_match('|\[attach\]href=\"(.*?)\" length=\"(.*?)\" type=\"(.*?)\" title=\"(.*?)\"|', $r, $matches);
1171 $attributes = ['type' => 'Document',
1172 'mediaType' => $matches[3],
1173 'url' => $matches[1],
1176 if (trim($matches[4]) != '') {
1177 $attributes['name'] = trim($matches[4]);
1180 $attachments[] = $attributes;
1185 if ($type != 'Note') {
1186 return $attachments;
1189 // Simplify image codes
1190 $body = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '[img]$3[/img]', $item['body']);
1192 // Grab all pictures without alternative descriptions and create attachments out of them
1193 if (preg_match_all("/\[img\]([^\[\]]*)\[\/img\]/Usi", $body, $pictures)) {
1194 foreach ($pictures[1] as $picture) {
1195 $imgdata = Images::getInfoFromURLCached($picture);
1197 $attachments[] = ['type' => 'Document',
1198 'mediaType' => $imgdata['mime'],
1205 // Grab all pictures with alternative description and create attachments out of them
1206 if (preg_match_all("/\[img=([^\[\]]*)\]([^\[\]]*)\[\/img\]/Usi", $body, $pictures, PREG_SET_ORDER)) {
1207 foreach ($pictures as $picture) {
1208 $imgdata = Images::getInfoFromURLCached($picture[1]);
1210 $attachments[] = ['type' => 'Document',
1211 'mediaType' => $imgdata['mime'],
1212 'url' => $picture[1],
1213 'name' => $picture[2]];
1218 return $attachments;
1222 * Callback function to replace a Friendica style mention in a mention that is used on AP
1224 * @param array $match Matching values for the callback
1225 * @return string Replaced mention
1226 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1228 private static function mentionCallback($match)
1230 if (empty($match[1])) {
1234 $data = Contact::getByURL($match[1], false, ['url', 'nick']);
1235 if (empty($data['nick'])) {
1239 return '@[url=' . $data['url'] . ']' . $data['nick'] . '[/url]';
1243 * Remove image elements since they are added as attachment
1245 * @param string $body
1247 * @return string with removed images
1249 private static function removePictures($body)
1251 // Simplify image codes
1252 $body = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '[img]$3[/img]', $body);
1253 $body = preg_replace("/\[img\=(.*?)\](.*?)\[\/img\]/ism", '[img]$1[/img]', $body);
1255 // Now remove local links
1256 $body = preg_replace_callback(
1257 '/\[url=([^\[\]]*)\]\[img\](.*)\[\/img\]\[\/url\]/Usi',
1259 // We remove the link when it is a link to a local photo page
1260 if (Photo::isLocalPage($match[1])) {
1263 // otherwise we just return the link
1264 return '[url]' . $match[1] . '[/url]';
1269 // Remove all pictures
1270 $body = preg_replace("/\[img\]([^\[\]]*)\[\/img\]/Usi", '', $body);
1276 * Fetches the "context" value for a givem item array from the "conversation" table
1278 * @param array $item
1280 * @return string with context url
1281 * @throws \Exception
1283 private static function fetchContextURLForItem($item)
1285 $conversation = DBA::selectFirst('conversation', ['conversation-href', 'conversation-uri'], ['item-uri' => $item['parent-uri']]);
1286 if (DBA::isResult($conversation) && !empty($conversation['conversation-href'])) {
1287 $context_uri = $conversation['conversation-href'];
1288 } elseif (DBA::isResult($conversation) && !empty($conversation['conversation-uri'])) {
1289 $context_uri = $conversation['conversation-uri'];
1291 $context_uri = $item['parent-uri'] . '#context';
1293 return $context_uri;
1297 * Returns if the post contains sensitive content ("nsfw")
1299 * @param integer $uri_id
1302 * @throws \Exception
1304 private static function isSensitive($uri_id)
1306 return DBA::exists('tag-view', ['uri-id' => $uri_id, 'name' => 'nsfw']);
1310 * Creates event data
1312 * @param array $item
1314 * @return array with the event data
1315 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1317 public static function createEvent($item)
1320 $event['name'] = $item['event-summary'];
1321 $event['content'] = BBCode::convert($item['event-desc'], false, BBCode::ACTIVITYPUB);
1322 $event['startTime'] = DateTimeFormat::utc($item['event-start'] . '+00:00', DateTimeFormat::ATOM);
1324 if (!$item['event-nofinish']) {
1325 $event['endTime'] = DateTimeFormat::utc($item['event-finish'] . '+00:00', DateTimeFormat::ATOM);
1328 if (!empty($item['event-location'])) {
1329 $item['location'] = $item['event-location'];
1330 $event['location'] = self::createLocation($item);
1337 * Creates a note/article object array
1339 * @param array $item
1341 * @return array with the object data
1342 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1343 * @throws \ImagickException
1345 public static function createNote($item)
1351 if ($item['event-type'] == 'event') {
1353 } elseif (!empty($item['title'])) {
1359 if ($item['deleted']) {
1360 $type = 'Tombstone';
1364 $data['id'] = $item['uri'];
1365 $data['type'] = $type;
1367 if ($item['deleted']) {
1371 $data['summary'] = BBCode::toPlaintext(BBCode::getAbstract($item['body'], Protocol::ACTIVITYPUB));
1373 if ($item['uri'] != $item['thr-parent']) {
1374 $data['inReplyTo'] = $item['thr-parent'];
1376 $data['inReplyTo'] = null;
1379 $data['diaspora:guid'] = $item['guid'];
1380 $data['published'] = DateTimeFormat::utc($item['created'] . '+00:00', DateTimeFormat::ATOM);
1382 if ($item['created'] != $item['edited']) {
1383 $data['updated'] = DateTimeFormat::utc($item['edited'] . '+00:00', DateTimeFormat::ATOM);
1386 $data['url'] = $item['plink'];
1387 $data['attributedTo'] = $item['author-link'];
1388 $data['sensitive'] = self::isSensitive($item['uri-id']);
1389 $data['context'] = self::fetchContextURLForItem($item);
1391 if (!empty($item['title'])) {
1392 $data['name'] = BBCode::toPlaintext($item['title'], false);
1395 $permission_block = self::createPermissionBlockForItem($item, false);
1397 $body = $item['body'];
1399 if (empty($item['uid']) || !Feature::isEnabled($item['uid'], 'explicit_mentions')) {
1400 $body = self::prependMentions($body, $item['uri-id']);
1403 if ($type == 'Note') {
1404 $body = self::removePictures($body);
1405 } elseif (($type == 'Article') && empty($data['summary'])) {
1406 $data['summary'] = BBCode::toPlaintext(Plaintext::shorten(self::removePictures($body), 1000));
1409 if ($type == 'Event') {
1410 $data = array_merge($data, self::createEvent($item));
1412 $regexp = "/[@!]\[url\=([^\[\]]*)\].*?\[\/url\]/ism";
1413 $body = preg_replace_callback($regexp, ['self', 'mentionCallback'], $body);
1415 $data['content'] = BBCode::convert($body, false, BBCode::ACTIVITYPUB);
1418 // The regular "content" field does contain a minimized HTML. This is done since systems like
1419 // Mastodon has got problems with - for example - embedded pictures.
1420 // The contentMap does contain the unmodified HTML.
1421 $language = self::getLanguage($item);
1422 if (!empty($language)) {
1423 $regexp = "/[@!]\[url\=([^\[\]]*)\].*?\[\/url\]/ism";
1424 $richbody = preg_replace_callback($regexp, ['self', 'mentionCallback'], $item['body']);
1425 $richbody = BBCode::removeAttachment($richbody);
1427 $data['contentMap'][$language] = BBCode::convert($richbody, false);
1430 $data['source'] = ['content' => $item['body'], 'mediaType' => "text/bbcode"];
1432 if (!empty($item['signed_text']) && ($item['uri'] != $item['thr-parent'])) {
1433 $data['diaspora:comment'] = $item['signed_text'];
1436 $data['attachment'] = self::createAttachmentList($item, $type);
1437 $data['tag'] = self::createTagList($item);
1439 if (empty($data['location']) && (!empty($item['coord']) || !empty($item['location']))) {
1440 $data['location'] = self::createLocation($item);
1443 if (!empty($item['app'])) {
1444 $data['generator'] = ['type' => 'Application', 'name' => $item['app']];
1447 $data = array_merge($data, $permission_block);
1453 * Fetches the language from the post, the user or the system.
1455 * @param array $item
1457 * @return string language string
1459 private static function getLanguage(array $item)
1461 // Try to fetch the language from the post itself
1462 if (!empty($item['language'])) {
1463 $languages = array_keys(json_decode($item['language'], true));
1464 if (!empty($languages[0])) {
1465 return $languages[0];
1469 // Otherwise use the user's language
1470 if (!empty($item['uid'])) {
1471 $user = DBA::selectFirst('user', ['language'], ['uid' => $item['uid']]);
1472 if (!empty($user['language'])) {
1473 return $user['language'];
1477 // And finally just use the system language
1478 return DI::config()->get('system', 'language');
1482 * Creates an an "add tag" entry
1484 * @param array $item
1485 * @param array $data activity data
1487 * @return array with activity data for adding tags
1488 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1489 * @throws \ImagickException
1491 private static function createAddTag($item, $data)
1493 $object = XML::parseString($item['object']);
1494 $target = XML::parseString($item["target"]);
1496 $data['diaspora:guid'] = $item['guid'];
1497 $data['actor'] = $item['author-link'];
1498 $data['target'] = (string)$target->id;
1499 $data['summary'] = BBCode::toPlaintext($item['body']);
1500 $data['object'] = ['id' => (string)$object->id, 'type' => 'tag', 'name' => (string)$object->title, 'content' => (string)$object->content];
1506 * Creates an announce object entry
1508 * @param array $item
1509 * @param array $data activity data
1511 * @return array with activity data
1512 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1513 * @throws \ImagickException
1515 private static function createAnnounce($item, $data)
1517 $orig_body = $item['body'];
1518 $announce = self::getAnnounceArray($item);
1519 if (empty($announce)) {
1520 $data['type'] = 'Create';
1521 $data['object'] = self::createNote($item);
1525 if (empty($announce['comment'])) {
1526 // Pure announce, without a quote
1527 $data['type'] = 'Announce';
1528 $data['object'] = $announce['object']['uri'];
1533 $data['type'] = 'Create';
1534 $item['body'] = $announce['comment'] . "\n" . $announce['object']['plink'];
1535 $data['object'] = self::createNote($item);
1537 /// @todo Finally descide how to implement this in AP. This is a possible way:
1538 $data['object']['attachment'][] = self::createNote($announce['object']);
1540 $data['object']['source']['content'] = $orig_body;
1545 * Return announce related data if the item is an annunce
1547 * @param array $item
1551 public static function getAnnounceArray($item)
1553 $reshared = Item::getShareArray($item);
1554 if (empty($reshared['guid'])) {
1558 $reshared_item = Item::selectFirst([], ['guid' => $reshared['guid']]);
1559 if (!DBA::isResult($reshared_item)) {
1563 if (!in_array($reshared_item['network'], [Protocol::ACTIVITYPUB, Protocol::DFRN])) {
1567 $profile = APContact::getByURL($reshared_item['author-link'], false);
1568 if (empty($profile)) {
1572 return ['object' => $reshared_item, 'actor' => $profile, 'comment' => $reshared['comment']];
1576 * Checks if the provided item array is an announce
1578 * @param array $item
1582 public static function isAnnounce($item)
1584 if (!empty($item['verb']) && ($item['verb'] == Activity::ANNOUNCE)) {
1588 $announce = self::getAnnounceArray($item);
1589 if (empty($announce)) {
1593 return empty($announce['comment']);
1597 * Creates an activity id for a given contact id
1599 * @param integer $cid Contact ID of target
1601 * @return bool|string activity id
1603 public static function activityIDFromContact($cid)
1605 $contact = DBA::selectFirst('contact', ['uid', 'id', 'created'], ['id' => $cid]);
1606 if (!DBA::isResult($contact)) {
1610 $hash = hash('ripemd128', $contact['uid'].'-'.$contact['id'].'-'.$contact['created']);
1611 $uuid = substr($hash, 0, 8). '-' . substr($hash, 8, 4) . '-' . substr($hash, 12, 4) . '-' . substr($hash, 16, 4) . '-' . substr($hash, 20, 12);
1612 return DI::baseUrl() . '/activity/' . $uuid;
1616 * Transmits a contact suggestion to a given inbox
1618 * @param integer $uid User ID
1619 * @param string $inbox Target inbox
1620 * @param integer $suggestion_id Suggestion ID
1622 * @return boolean was the transmission successful?
1623 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1625 public static function sendContactSuggestion($uid, $inbox, $suggestion_id)
1627 $owner = User::getOwnerDataById($uid);
1629 $suggestion = DI::fsuggest()->getById($suggestion_id);
1631 $data = ['@context' => ActivityPub::CONTEXT,
1632 'id' => DI::baseUrl() . '/activity/' . System::createGUID(),
1633 'type' => 'Announce',
1634 'actor' => $owner['url'],
1635 'object' => $suggestion->url,
1636 'content' => $suggestion->note,
1637 'instrument' => self::getService(),
1638 'to' => [ActivityPub::PUBLIC_COLLECTION],
1641 $signed = LDSignature::sign($data, $owner);
1643 Logger::log('Deliver profile deletion for user ' . $uid . ' to ' . $inbox . ' via ActivityPub', Logger::DEBUG);
1644 return HTTPSignature::transmit($signed, $inbox, $uid);
1648 * Transmits a profile relocation to a given inbox
1650 * @param integer $uid User ID
1651 * @param string $inbox Target inbox
1653 * @return boolean was the transmission successful?
1654 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1656 public static function sendProfileRelocation($uid, $inbox)
1658 $owner = User::getOwnerDataById($uid);
1660 $data = ['@context' => ActivityPub::CONTEXT,
1661 'id' => DI::baseUrl() . '/activity/' . System::createGUID(),
1662 'type' => 'dfrn:relocate',
1663 'actor' => $owner['url'],
1664 'object' => $owner['url'],
1665 'published' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
1666 'instrument' => self::getService(),
1667 'to' => [ActivityPub::PUBLIC_COLLECTION],
1670 $signed = LDSignature::sign($data, $owner);
1672 Logger::log('Deliver profile relocation for user ' . $uid . ' to ' . $inbox . ' via ActivityPub', Logger::DEBUG);
1673 return HTTPSignature::transmit($signed, $inbox, $uid);
1677 * Transmits a profile deletion to a given inbox
1679 * @param integer $uid User ID
1680 * @param string $inbox Target inbox
1682 * @return boolean was the transmission successful?
1683 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1685 public static function sendProfileDeletion($uid, $inbox)
1687 $owner = User::getOwnerDataById($uid);
1689 if (empty($owner)) {
1690 Logger::error('No owner data found, the deletion message cannot be processed.', ['user' => $uid]);
1694 if (empty($owner['uprvkey'])) {
1695 Logger::error('No private key for owner found, the deletion message cannot be processed.', ['user' => $uid]);
1699 $data = ['@context' => ActivityPub::CONTEXT,
1700 'id' => DI::baseUrl() . '/activity/' . System::createGUID(),
1702 'actor' => $owner['url'],
1703 'object' => $owner['url'],
1704 'published' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
1705 'instrument' => self::getService(),
1706 'to' => [ActivityPub::PUBLIC_COLLECTION],
1709 $signed = LDSignature::sign($data, $owner);
1711 Logger::log('Deliver profile deletion for user ' . $uid . ' to ' . $inbox . ' via ActivityPub', Logger::DEBUG);
1712 return HTTPSignature::transmit($signed, $inbox, $uid);
1716 * Transmits a profile change to a given inbox
1718 * @param integer $uid User ID
1719 * @param string $inbox Target inbox
1721 * @return boolean was the transmission successful?
1722 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1723 * @throws \ImagickException
1725 public static function sendProfileUpdate($uid, $inbox)
1727 $owner = User::getOwnerDataById($uid);
1728 $profile = APContact::getByURL($owner['url']);
1730 $data = ['@context' => ActivityPub::CONTEXT,
1731 'id' => DI::baseUrl() . '/activity/' . System::createGUID(),
1733 'actor' => $owner['url'],
1734 'object' => self::getProfile($uid),
1735 'published' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
1736 'instrument' => self::getService(),
1737 'to' => [$profile['followers']],
1740 $signed = LDSignature::sign($data, $owner);
1742 Logger::log('Deliver profile update for user ' . $uid . ' to ' . $inbox . ' via ActivityPub', Logger::DEBUG);
1743 return HTTPSignature::transmit($signed, $inbox, $uid);
1747 * Transmits a given activity to a target
1749 * @param string $activity Type name
1750 * @param string $target Target profile
1751 * @param integer $uid User ID
1753 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1754 * @throws \ImagickException
1755 * @throws \Exception
1757 public static function sendActivity($activity, $target, $uid, $id = '')
1759 $profile = APContact::getByURL($target);
1760 if (empty($profile['inbox'])) {
1761 Logger::warning('No inbox found for target', ['target' => $target, 'profile' => $profile]);
1765 $owner = User::getOwnerDataById($uid);
1768 $id = DI::baseUrl() . '/activity/' . System::createGUID();
1771 $data = ['@context' => ActivityPub::CONTEXT,
1773 'type' => $activity,
1774 'actor' => $owner['url'],
1775 'object' => $profile['url'],
1776 'instrument' => self::getService(),
1777 'to' => [$profile['url']]];
1779 Logger::log('Sending activity ' . $activity . ' to ' . $target . ' for user ' . $uid, Logger::DEBUG);
1781 $signed = LDSignature::sign($data, $owner);
1782 return HTTPSignature::transmit($signed, $profile['inbox'], $uid);
1786 * Transmits a "follow object" activity to a target
1787 * This is a preparation for sending automated "follow" requests when receiving "Announce" messages
1789 * @param string $object Object URL
1790 * @param string $target Target profile
1791 * @param integer $uid User ID
1793 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1794 * @throws \ImagickException
1795 * @throws \Exception
1797 public static function sendFollowObject($object, $target, $uid = 0)
1799 $profile = APContact::getByURL($target);
1800 if (empty($profile['inbox'])) {
1801 Logger::warning('No inbox found for target', ['target' => $target, 'profile' => $profile]);
1806 // Fetch the list of administrators
1807 $admin_mail = explode(',', str_replace(' ', '', DI::config()->get('config', 'admin_email')));
1809 // We need to use some user as a sender. It doesn't care who it will send. We will use an administrator account.
1810 $condition = ['verified' => true, 'blocked' => false, 'account_removed' => false, 'account_expired' => false, 'email' => $admin_mail];
1811 $first_user = DBA::selectFirst('user', ['uid'], $condition);
1812 $uid = $first_user['uid'];
1815 $condition = ['verb' => Activity::FOLLOW, 'uid' => 0, 'parent-uri' => $object,
1816 'author-id' => Contact::getPublicIdByUserId($uid)];
1817 if (Item::exists($condition)) {
1818 Logger::log('Follow for ' . $object . ' for user ' . $uid . ' does already exist.', Logger::DEBUG);
1822 $owner = User::getOwnerDataById($uid);
1824 $data = ['@context' => ActivityPub::CONTEXT,
1825 'id' => DI::baseUrl() . '/activity/' . System::createGUID(),
1827 'actor' => $owner['url'],
1828 'object' => $object,
1829 'instrument' => self::getService(),
1830 'to' => [$profile['url']]];
1832 Logger::log('Sending follow ' . $object . ' to ' . $target . ' for user ' . $uid, Logger::DEBUG);
1834 $signed = LDSignature::sign($data, $owner);
1835 return HTTPSignature::transmit($signed, $profile['inbox'], $uid);
1839 * Transmit a message that the contact request had been accepted
1841 * @param string $target Target profile
1843 * @param integer $uid User ID
1844 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1845 * @throws \ImagickException
1847 public static function sendContactAccept($target, $id, $uid)
1849 $profile = APContact::getByURL($target);
1850 if (empty($profile['inbox'])) {
1851 Logger::warning('No inbox found for target', ['target' => $target, 'profile' => $profile]);
1855 $owner = User::getOwnerDataById($uid);
1856 $data = ['@context' => ActivityPub::CONTEXT,
1857 'id' => DI::baseUrl() . '/activity/' . System::createGUID(),
1859 'actor' => $owner['url'],
1861 'id' => (string)$id,
1863 'actor' => $profile['url'],
1864 'object' => $owner['url']
1866 'instrument' => self::getService(),
1867 'to' => [$profile['url']]];
1869 Logger::debug('Sending accept to ' . $target . ' for user ' . $uid . ' with id ' . $id);
1871 $signed = LDSignature::sign($data, $owner);
1872 HTTPSignature::transmit($signed, $profile['inbox'], $uid);
1876 * Reject a contact request or terminates the contact relation
1878 * @param string $target Target profile
1880 * @param integer $uid User ID
1881 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1882 * @throws \ImagickException
1884 public static function sendContactReject($target, $id, $uid)
1886 $profile = APContact::getByURL($target);
1887 if (empty($profile['inbox'])) {
1888 Logger::warning('No inbox found for target', ['target' => $target, 'profile' => $profile]);
1892 $owner = User::getOwnerDataById($uid);
1893 $data = ['@context' => ActivityPub::CONTEXT,
1894 'id' => DI::baseUrl() . '/activity/' . System::createGUID(),
1896 'actor' => $owner['url'],
1898 'id' => (string)$id,
1900 'actor' => $profile['url'],
1901 'object' => $owner['url']
1903 'instrument' => self::getService(),
1904 'to' => [$profile['url']]];
1906 Logger::debug('Sending reject to ' . $target . ' for user ' . $uid . ' with id ' . $id);
1908 $signed = LDSignature::sign($data, $owner);
1909 HTTPSignature::transmit($signed, $profile['inbox'], $uid);
1913 * Transmits a message that we don't want to follow this contact anymore
1915 * @param string $target Target profile
1916 * @param integer $uid User ID
1917 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1918 * @throws \ImagickException
1919 * @throws \Exception
1921 public static function sendContactUndo($target, $cid, $uid)
1923 $profile = APContact::getByURL($target);
1924 if (empty($profile['inbox'])) {
1925 Logger::warning('No inbox found for target', ['target' => $target, 'profile' => $profile]);
1929 $object_id = self::activityIDFromContact($cid);
1930 if (empty($object_id)) {
1934 $id = DI::baseUrl() . '/activity/' . System::createGUID();
1936 $owner = User::getOwnerDataById($uid);
1937 $data = ['@context' => ActivityPub::CONTEXT,
1940 'actor' => $owner['url'],
1941 'object' => ['id' => $object_id, 'type' => 'Follow',
1942 'actor' => $owner['url'],
1943 'object' => $profile['url']],
1944 'instrument' => self::getService(),
1945 'to' => [$profile['url']]];
1947 Logger::log('Sending undo to ' . $target . ' for user ' . $uid . ' with id ' . $id, Logger::DEBUG);
1949 $signed = LDSignature::sign($data, $owner);
1950 HTTPSignature::transmit($signed, $profile['inbox'], $uid);
1953 private static function prependMentions($body, int $uriid)
1957 foreach (Tag::getByURIId($uriid, [Tag::IMPLICIT_MENTION]) as $tag) {
1958 $profile = Contact::getByURL($tag['url'], false, ['addr', 'contact-type', 'nick']);
1959 if (!empty($profile['addr'])
1960 && $profile['contact-type'] != Contact::TYPE_COMMUNITY
1961 && !strstr($body, $profile['addr'])
1962 && !strstr($body, $tag['url'])
1964 $mentions[] = '@[url=' . $tag['url'] . ']' . $profile['nick'] . '[/url]';
1968 $mentions[] = $body;
1970 return implode(' ', $mentions);