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 numbe
147 * @return array of posts
148 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
149 * @throws \ImagickException
151 public static function getOutbox($owner, $page = null)
153 $public_contact = Contact::getIdForURL($owner['url']);
155 $condition = ['uid' => 0, 'contact-id' => $public_contact, 'author-id' => $public_contact,
156 'private' => [Item::PUBLIC, Item::UNLISTED], 'gravity' => [GRAVITY_PARENT, GRAVITY_COMMENT],
157 'deleted' => false, 'visible' => true, 'moderated' => false];
158 $count = DBA::count('item', $condition);
160 $data = ['@context' => ActivityPub::CONTEXT];
161 $data['id'] = DI::baseUrl() . '/outbox/' . $owner['nickname'];
162 $data['type'] = 'OrderedCollection';
163 $data['totalItems'] = $count;
166 $data['first'] = DI::baseUrl() . '/outbox/' . $owner['nickname'] . '?page=1';
168 $data['type'] = 'OrderedCollectionPage';
171 $condition['parent-network'] = Protocol::NATIVE_SUPPORT;
173 $items = Item::select(['id'], $condition, ['limit' => [($page - 1) * 20, 20], 'order' => ['created' => true]]);
174 while ($item = Item::fetch($items)) {
175 $activity = self::createActivityFromItem($item['id'], true);
176 $activity['type'] = $activity['type'] == 'Update' ? 'Create' : $activity['type'];
178 // Only list "Create" activity objects here, no reshares
179 if (!empty($activity['object']) && ($activity['type'] == 'Create')) {
180 $list[] = $activity['object'];
185 $data['next'] = DI::baseUrl() . '/outbox/' . $owner['nickname'] . '?page=' . ($page + 1);
188 $data['partOf'] = DI::baseUrl() . '/outbox/' . $owner['nickname'];
190 $data['orderedItems'] = $list;
197 * Return the service array containing information the used software and it's url
199 * @return array with service data
201 private static function getService()
203 return ['type' => 'Service',
204 'name' => FRIENDICA_PLATFORM . " '" . FRIENDICA_CODENAME . "' " . FRIENDICA_VERSION . '-' . DB_UPDATE_VERSION,
205 'url' => DI::baseUrl()->get()];
209 * Return the ActivityPub profile of the given user
211 * @param integer $uid User ID
212 * @return array with profile data
213 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
215 public static function getProfile($uid)
217 $condition = ['uid' => $uid, 'blocked' => false, 'account_expired' => false,
218 'account_removed' => false, 'verified' => true];
219 $fields = ['guid', 'nickname', 'pubkey', 'account-type', 'page-flags'];
220 $user = DBA::selectFirst('user', $fields, $condition);
221 if (!DBA::isResult($user)) {
225 $fields = ['locality', 'region', 'country-name'];
226 $profile = DBA::selectFirst('profile', $fields, ['uid' => $uid]);
227 if (!DBA::isResult($profile)) {
231 $fields = ['name', 'url', 'location', 'about', 'avatar', 'photo'];
232 $contact = DBA::selectFirst('contact', $fields, ['uid' => $uid, 'self' => true]);
233 if (!DBA::isResult($contact)) {
237 $data = ['@context' => ActivityPub::CONTEXT];
238 $data['id'] = $contact['url'];
239 $data['diaspora:guid'] = $user['guid'];
240 $data['type'] = ActivityPub::ACCOUNT_TYPES[$user['account-type']];
241 $data['following'] = DI::baseUrl() . '/following/' . $user['nickname'];
242 $data['followers'] = DI::baseUrl() . '/followers/' . $user['nickname'];
243 $data['inbox'] = DI::baseUrl() . '/inbox/' . $user['nickname'];
244 $data['outbox'] = DI::baseUrl() . '/outbox/' . $user['nickname'];
245 $data['preferredUsername'] = $user['nickname'];
246 $data['name'] = $contact['name'];
247 $data['vcard:hasAddress'] = ['@type' => 'vcard:Home', 'vcard:country-name' => $profile['country-name'],
248 'vcard:region' => $profile['region'], 'vcard:locality' => $profile['locality']];
249 $data['summary'] = BBCode::convert($contact['about'], false);
250 $data['url'] = $contact['url'];
251 $data['manuallyApprovesFollowers'] = in_array($user['page-flags'], [User::PAGE_FLAGS_NORMAL, User::PAGE_FLAGS_PRVGROUP]);
252 $data['publicKey'] = ['id' => $contact['url'] . '#main-key',
253 'owner' => $contact['url'],
254 'publicKeyPem' => $user['pubkey']];
255 $data['endpoints'] = ['sharedInbox' => DI::baseUrl() . '/inbox'];
256 $data['icon'] = ['type' => 'Image',
257 'url' => $contact['photo']];
259 $data['generator'] = self::getService();
261 // tags: https://kitty.town/@inmysocks/100656097926961126.json
266 * @param string $username
268 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
270 public static function getDeletedUser($username)
273 '@context' => ActivityPub::CONTEXT,
274 'id' => DI::baseUrl() . '/profile/' . $username,
275 'type' => 'Tombstone',
276 'published' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
277 'updated' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
278 'deleted' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
283 * Returns an array with permissions of a given item array
287 * @return array with permissions
288 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
289 * @throws \ImagickException
291 private static function fetchPermissionBlockFromConversation($item)
293 if (empty($item['thr-parent'])) {
297 $condition = ['item-uri' => $item['thr-parent'], 'protocol' => Conversation::PARCEL_ACTIVITYPUB];
298 $conversation = DBA::selectFirst('conversation', ['source'], $condition);
299 if (!DBA::isResult($conversation)) {
303 $activity = json_decode($conversation['source'], true);
305 $actor = JsonLD::fetchElement($activity, 'actor', 'id');
306 $profile = APContact::getByURL($actor);
308 $item_profile = APContact::getByURL($item['author-link']);
309 $exclude[] = $item['author-link'];
311 if ($item['gravity'] == GRAVITY_PARENT) {
312 $exclude[] = $item['owner-link'];
315 $permissions['to'][] = $actor;
317 foreach (['to', 'cc', 'bto', 'bcc'] as $element) {
318 if (empty($activity[$element])) {
321 if (is_string($activity[$element])) {
322 $activity[$element] = [$activity[$element]];
325 foreach ($activity[$element] as $receiver) {
326 if (empty($receiver)) {
330 if (!empty($profile['followers']) && $receiver == $profile['followers'] && !empty($item_profile['followers'])) {
331 $permissions[$element][] = $item_profile['followers'];
332 } elseif (!in_array($receiver, $exclude)) {
333 $permissions[$element][] = $receiver;
341 * Creates an array of permissions from an item thread
343 * @param array $item Item array
344 * @param boolean $blindcopy addressing via "bcc" or "cc"?
345 * @param integer $last_id Last item id for adding receivers
346 * @param boolean $forum_mode "true" means that we are sending content to a forum
348 * @return array with permission data
349 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
350 * @throws \ImagickException
352 private static function createPermissionBlockForItem($item, $blindcopy, $last_id = 0, $forum_mode = false)
355 $last_id = $item['id'];
361 // Check if we should always deliver our stuff via BCC
362 if (!empty($item['uid'])) {
363 $profile = User::getOwnerDataById($item['uid']);
364 if (!empty($profile)) {
365 $always_bcc = $profile['hide-friends'];
366 $isforum = $profile['account-type'] == User::ACCOUNT_TYPE_COMMUNITY;
370 if (DI::config()->get('system', 'ap_always_bcc')) {
374 if ((self::isAnnounce($item) && !$isforum) || DI::config()->get('debug', 'total_ap_delivery')) {
375 // Will be activated in a later step
376 $networks = Protocol::FEDERATED;
378 // For now only send to these contacts:
379 $networks = [Protocol::ACTIVITYPUB, Protocol::OSTATUS];
382 $data = ['to' => [], 'cc' => [], 'bcc' => []];
384 if ($item['gravity'] == GRAVITY_PARENT) {
385 $actor_profile = APContact::getByURL($item['owner-link']);
387 $actor_profile = APContact::getByURL($item['author-link']);
390 $terms = Tag::getByURIId($item['uri-id'], [Tag::MENTION, Tag::IMPLICIT_MENTION, Tag::EXCLUSIVE_MENTION]);
392 if ($item['private'] != Item::PRIVATE) {
393 // Directly mention the original author upon a quoted reshare.
394 // Else just ensure that the original author receives the reshare.
395 $announce = self::getAnnounceArray($item);
396 if (!empty($announce['comment'])) {
397 $data['to'][] = $announce['actor']['url'];
398 } elseif (!empty($announce)) {
399 $data['cc'][] = $announce['actor']['url'];
402 $data = array_merge($data, self::fetchPermissionBlockFromConversation($item));
404 // Check if the item is completely public or unlisted
405 if ($item['private'] == Item::PUBLIC) {
406 $data['to'][] = ActivityPub::PUBLIC_COLLECTION;
408 $data['cc'][] = ActivityPub::PUBLIC_COLLECTION;
411 foreach ($terms as $term) {
412 $profile = APContact::getByURL($term['url'], false);
413 if (!empty($profile)) {
414 $data['to'][] = $profile['url'];
418 $receiver_list = Item::enumeratePermissions($item, true);
420 foreach ($terms as $term) {
421 $cid = Contact::getIdForURL($term['url'], $item['uid']);
422 if (!empty($cid) && in_array($cid, $receiver_list)) {
423 $contact = DBA::selectFirst('contact', ['url', 'network', 'protocol'], ['id' => $cid]);
424 if (!DBA::isResult($contact) || (!in_array($contact['network'], $networks) && ($contact['protocol'] != Protocol::ACTIVITYPUB))) {
428 if ($isforum && DBA::isResult($contact) && ($contact['dfrn'] == Protocol::DFRN)) {
432 if (!empty($profile = APContact::getByURL($contact['url'], false))) {
433 $data['to'][] = $profile['url'];
438 foreach ($receiver_list as $receiver) {
439 $contact = DBA::selectFirst('contact', ['url', 'hidden', 'network', 'protocol'], ['id' => $receiver]);
440 if (!DBA::isResult($contact) || (!in_array($contact['network'], $networks) && ($contact['protocol'] != Protocol::ACTIVITYPUB))) {
444 if ($isforum && DBA::isResult($contact) && ($contact['dfrn'] == Protocol::DFRN)) {
448 if (!empty($profile = APContact::getByURL($contact['url'], false))) {
449 if ($contact['hidden'] || $always_bcc) {
450 $data['bcc'][] = $profile['url'];
452 $data['cc'][] = $profile['url'];
458 if (!empty($item['parent'])) {
459 $parents = Item::select(['id', 'author-link', 'owner-link', 'gravity', 'uri'], ['parent' => $item['parent']]);
460 while ($parent = Item::fetch($parents)) {
461 if ($parent['gravity'] == GRAVITY_PARENT) {
462 $profile = APContact::getByURL($parent['owner-link'], false);
463 if (!empty($profile)) {
464 if ($item['gravity'] != GRAVITY_PARENT) {
465 // Comments to forums are directed to the forum
466 // But comments to forums aren't directed to the followers collection
467 // This rule is only valid when the actor isn't the forum.
468 // The forum needs to transmit their content to their followers.
469 if (($profile['type'] == 'Group') && ($profile['url'] != $actor_profile['url'])) {
470 $data['to'][] = $profile['url'];
472 $data['cc'][] = $profile['url'];
473 if (($item['private'] != Item::PRIVATE) && !empty($actor_profile['followers'])) {
474 $data['cc'][] = $actor_profile['followers'];
478 // Public thread parent post always are directed to the followers
479 if (($item['private'] != Item::PRIVATE) && !$forum_mode) {
480 $data['cc'][] = $actor_profile['followers'];
486 // Don't include data from future posts
487 if ($parent['id'] >= $last_id) {
491 $profile = APContact::getByURL($parent['author-link'], false);
492 if (!empty($profile)) {
493 if (($profile['type'] == 'Group') || ($parent['uri'] == $item['thr-parent'])) {
494 $data['to'][] = $profile['url'];
496 $data['cc'][] = $profile['url'];
500 DBA::close($parents);
503 $data['to'] = array_unique($data['to']);
504 $data['cc'] = array_unique($data['cc']);
505 $data['bcc'] = array_unique($data['bcc']);
507 if (($key = array_search($item['author-link'], $data['to'])) !== false) {
508 unset($data['to'][$key]);
511 if (($key = array_search($item['author-link'], $data['cc'])) !== false) {
512 unset($data['cc'][$key]);
515 if (($key = array_search($item['author-link'], $data['bcc'])) !== false) {
516 unset($data['bcc'][$key]);
519 foreach ($data['to'] as $to) {
520 if (($key = array_search($to, $data['cc'])) !== false) {
521 unset($data['cc'][$key]);
524 if (($key = array_search($to, $data['bcc'])) !== false) {
525 unset($data['bcc'][$key]);
529 foreach ($data['cc'] as $cc) {
530 if (($key = array_search($cc, $data['bcc'])) !== false) {
531 unset($data['bcc'][$key]);
535 $receivers = ['to' => array_values($data['to']), 'cc' => array_values($data['cc']), 'bcc' => array_values($data['bcc'])];
538 unset($receivers['bcc']);
545 * Check if an inbox is archived
547 * @param string $url Inbox url
549 * @return boolean "true" if inbox is archived
551 private static function archivedInbox($url)
553 return DBA::exists('inbox-status', ['url' => $url, 'archive' => true]);
557 * Fetches a list of inboxes of followers of a given user
559 * @param integer $uid User ID
560 * @param boolean $personal fetch personal inboxes
562 * @return array of follower inboxes
563 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
564 * @throws \ImagickException
566 public static function fetchTargetInboxesforUser($uid, $personal = false)
572 if (!empty($item['uid'])) {
573 $profile = User::getOwnerDataById($item['uid']);
574 if (!empty($profile)) {
575 $isforum = $profile['account-type'] == User::ACCOUNT_TYPE_COMMUNITY;
579 if (DI::config()->get('debug', 'total_ap_delivery')) {
580 // Will be activated in a later step
581 $networks = Protocol::FEDERATED;
583 // For now only send to these contacts:
584 $networks = [Protocol::ACTIVITYPUB, Protocol::OSTATUS];
587 $condition = ['uid' => $uid, 'archive' => false, 'pending' => false];
590 $condition['rel'] = [Contact::FOLLOWER, Contact::FRIEND];
593 $contacts = DBA::select('contact', ['url', 'network', 'protocol'], $condition);
594 while ($contact = DBA::fetch($contacts)) {
595 if (Contact::isLocal($contact['url'])) {
599 if (!in_array($contact['network'], $networks) && ($contact['protocol'] != Protocol::ACTIVITYPUB)) {
603 if ($isforum && ($contact['dfrn'] == Protocol::DFRN)) {
607 if (Network::isUrlBlocked($contact['url'])) {
611 $profile = APContact::getByURL($contact['url'], false);
612 if (!empty($profile)) {
613 if (empty($profile['sharedinbox']) || $personal) {
614 $target = $profile['inbox'];
616 $target = $profile['sharedinbox'];
618 if (!self::archivedInbox($target)) {
619 $inboxes[$target] = $target;
623 DBA::close($contacts);
629 * Fetches an array of inboxes for the given item and user
631 * @param array $item Item array
632 * @param integer $uid User ID
633 * @param boolean $personal fetch personal inboxes
634 * @param integer $last_id Last item id for adding receivers
635 * @param boolean $forum_mode "true" means that we are sending content to a forum
636 * @return array with inboxes
637 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
638 * @throws \ImagickException
640 public static function fetchTargetInboxes($item, $uid, $personal = false, $last_id = 0, $forum_mode = false)
642 $permissions = self::createPermissionBlockForItem($item, true, $last_id, $forum_mode);
643 if (empty($permissions)) {
649 if ($item['gravity'] == GRAVITY_ACTIVITY) {
650 $item_profile = APContact::getByURL($item['author-link'], false);
652 $item_profile = APContact::getByURL($item['owner-link'], false);
655 $profile_uid = User::getIdForURL($item_profile['url']);
657 foreach (['to', 'cc', 'bto', 'bcc'] as $element) {
658 if (empty($permissions[$element])) {
662 $blindcopy = in_array($element, ['bto', 'bcc']);
664 foreach ($permissions[$element] as $receiver) {
665 if (empty($receiver) || Network::isUrlBlocked($receiver)) {
669 if ($item_profile && ($receiver == $item_profile['followers']) && ($uid == $profile_uid)) {
670 $inboxes = array_merge($inboxes, self::fetchTargetInboxesforUser($uid, $personal));
672 if (Contact::isLocal($receiver)) {
676 $profile = APContact::getByURL($receiver, false);
677 if (!empty($profile)) {
678 if (empty($profile['sharedinbox']) || $personal || $blindcopy) {
679 $target = $profile['inbox'];
681 $target = $profile['sharedinbox'];
683 if (!self::archivedInbox($target)) {
684 $inboxes[$target] = $target;
695 * Creates an array in the structure of the item table for a given mail id
697 * @param integer $mail_id
702 public static function ItemArrayFromMail($mail_id)
704 $mail = DBA::selectFirst('mail', [], ['id' => $mail_id]);
705 if (!DBA::isResult($mail)) {
709 $mail['uri-id'] = ItemURI::insert(['uri' => $mail['uri'], 'guid' => $mail['guid']]);
711 $reply = DBA::selectFirst('mail', ['uri'], ['parent-uri' => $mail['parent-uri'], 'reply' => false]);
713 // Making the post more compatible for Mastodon by:
714 // - Making it a note and not an article (no title)
715 // - Moving the title into the "summary" field that is used as a "content warning"
716 $mail['body'] = '[abstract]' . $mail['title'] . "[/abstract]\n" . $mail['body'];
719 $mail['author-link'] = $mail['owner-link'] = $mail['from-url'];
720 $mail['allow_cid'] = '<'.$mail['contact-id'].'>';
721 $mail['allow_gid'] = '';
722 $mail['deny_cid'] = '';
723 $mail['deny_gid'] = '';
724 $mail['private'] = true;
725 $mail['deleted'] = false;
726 $mail['edited'] = $mail['created'];
727 $mail['plink'] = $mail['uri'];
728 $mail['thr-parent'] = $reply['uri'];
729 $mail['gravity'] = ($mail['reply'] ? GRAVITY_COMMENT: GRAVITY_PARENT);
731 $mail['event-type'] = '';
732 $mail['attach'] = '';
740 * Creates an activity array for a given mail id
742 * @param integer $mail_id
743 * @param boolean $object_mode Is the activity item is used inside another object?
745 * @return array of activity
748 public static function createActivityFromMail($mail_id, $object_mode = false)
750 $mail = self::ItemArrayFromMail($mail_id);
751 $object = self::createNote($mail);
754 $data = ['@context' => ActivityPub::CONTEXT];
759 $data['id'] = $mail['uri'] . '/Create';
760 $data['type'] = 'Create';
761 $data['actor'] = $mail['author-link'];
762 $data['published'] = DateTimeFormat::utc($mail['created'] . '+00:00', DateTimeFormat::ATOM);
763 $data['instrument'] = self::getService();
764 $data = array_merge($data, self::createPermissionBlockForItem($mail, true));
766 if (empty($data['to']) && !empty($data['cc'])) {
767 $data['to'] = $data['cc'];
770 if (empty($data['to']) && !empty($data['bcc'])) {
771 $data['to'] = $data['bcc'];
777 $object['to'] = $data['to'];
778 $object['tag'] = [['type' => 'Mention', 'href' => $object['to'][0], 'name' => '']];
780 unset($object['cc']);
781 unset($object['bcc']);
783 $data['directMessage'] = true;
785 $data['object'] = $object;
787 $owner = User::getOwnerDataById($mail['uid']);
789 if (!$object_mode && !empty($owner)) {
790 return LDSignature::sign($data, $owner);
797 * Returns the activity type of a given item
801 * @return string with activity type
802 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
803 * @throws \ImagickException
805 private static function getTypeOfItem($item)
809 // Only check for a reshare, if it is a real reshare and no quoted reshare
810 if (strpos($item['body'], "[share") === 0) {
811 $announce = self::getAnnounceArray($item);
812 $reshared = !empty($announce);
817 } elseif ($item['verb'] == Activity::POST) {
818 if ($item['created'] == $item['edited']) {
823 } elseif ($item['verb'] == Activity::LIKE) {
825 } elseif ($item['verb'] == Activity::DISLIKE) {
827 } elseif ($item['verb'] == Activity::ATTEND) {
829 } elseif ($item['verb'] == Activity::ATTENDNO) {
831 } elseif ($item['verb'] == Activity::ATTENDMAYBE) {
832 $type = 'TentativeAccept';
833 } elseif ($item['verb'] == Activity::FOLLOW) {
835 } elseif ($item['verb'] == Activity::TAG) {
837 } elseif ($item['verb'] == Activity::ANNOUNCE) {
847 * Creates the activity or fetches it from the cache
849 * @param integer $item_id
850 * @param boolean $force Force new cache entry
852 * @return array with the activity
855 public static function createCachedActivityFromItem($item_id, $force = false)
857 $cachekey = 'APDelivery:createActivity:' . $item_id;
860 $data = DI::cache()->get($cachekey);
861 if (!is_null($data)) {
866 $data = self::createActivityFromItem($item_id);
868 DI::cache()->set($cachekey, $data, Duration::QUARTER_HOUR);
873 * Creates an activity array for a given item id
875 * @param integer $item_id
876 * @param boolean $object_mode Is the activity item is used inside another object?
878 * @return array of activity
881 public static function createActivityFromItem($item_id, $object_mode = false)
883 Logger::info('Fetching activity', ['item' => $item_id]);
884 $item = Item::selectFirst([], ['id' => $item_id, 'parent-network' => Protocol::NATIVE_SUPPORT]);
885 if (!DBA::isResult($item)) {
889 /// @todo This code should be removed by the end of the year 2020
890 if ($item['wall'] && ($item['uri'] == $item['parent-uri'])) {
891 $owner = User::getOwnerDataById($item['uid']);
892 if (($owner['account-type'] == User::ACCOUNT_TYPE_COMMUNITY) && ($item['author-link'] != $owner['url'])) {
895 // Disguise forum posts as reshares. Will later be converted to a real announce
896 $item['body'] = BBCode::getShareOpeningTag($item['author-name'], $item['author-link'], $item['author-avatar'],
897 $item['plink'], $item['created'], $item['guid']) . $item['body'] . '[/share]';
902 /// @todo This code should be activated by the end of the year 2020
903 // See also "tagDeliver";
904 // In case of a forum post ensure to return the original post if author and forum are on the same machine
905 if (!empty($item['forum_mode'])) {
906 $author = Contact::getById($item['author-id'], ['nurl']);
907 if (!empty($author['nurl'])) {
908 $self = Contact::selectFirst(['uid'], ['nurl' => $author['nurl'], 'self' => true]);
909 if (!empty($self['uid'])) {
910 $item = Item::selectFirst([], ['uri-id' => $item['uri-id'], 'uid' => $self['uid']]);
917 $condition = ['item-uri' => $item['uri'], 'protocol' => Conversation::PARCEL_ACTIVITYPUB];
918 $conversation = DBA::selectFirst('conversation', ['source'], $condition);
919 if (DBA::isResult($conversation)) {
920 $data = json_decode($conversation['source'], true);
921 if (!empty($data['type'])) {
922 if (in_array($data['type'], ['Create', 'Update'])) {
924 unset($data['@context']);
925 unset($data['signature']);
927 Logger::info('Return stored conversation', ['item' => $item_id]);
929 } elseif (in_array('as:' . $data['type'], Receiver::CONTENT_TYPES)) {
930 if (!empty($data['@context'])) {
931 $context = $data['@context'];
932 unset($data['@context']);
934 unset($data['actor']);
940 $type = self::getTypeOfItem($item);
944 $data = ['@context' => $context ?? ActivityPub::CONTEXT];
946 if ($item['deleted'] && ($item['gravity'] == GRAVITY_ACTIVITY)) {
948 } elseif ($item['deleted']) {
955 $data['id'] = $item['uri'] . '/' . $type;
956 $data['type'] = $type;
958 if (($type != 'Announce') || ($item['gravity'] != GRAVITY_PARENT)) {
959 $data['actor'] = $item['author-link'];
961 $data['actor'] = $item['owner-link'];
964 $data['published'] = DateTimeFormat::utc($item['created'] . '+00:00', DateTimeFormat::ATOM);
966 $data['instrument'] = self::getService();
968 $data = array_merge($data, self::createPermissionBlockForItem($item, false));
970 if (in_array($data['type'], ['Create', 'Update', 'Delete'])) {
971 $data['object'] = $object ?? self::createNote($item);
972 } elseif ($data['type'] == 'Add') {
973 $data = self::createAddTag($item, $data);
974 } elseif ($data['type'] == 'Announce') {
975 if ($item['verb'] == ACTIVITY::ANNOUNCE) {
976 $data['object'] = $item['thr-parent'];
978 $data = self::createAnnounce($item, $data);
980 } elseif ($data['type'] == 'Follow') {
981 $data['object'] = $item['parent-uri'];
982 } elseif ($data['type'] == 'Undo') {
983 $data['object'] = self::createActivityFromItem($item_id, true);
985 $data['diaspora:guid'] = $item['guid'];
986 if (!empty($item['signed_text'])) {
987 $data['diaspora:like'] = $item['signed_text'];
989 $data['object'] = $item['thr-parent'];
992 if (!empty($item['contact-uid'])) {
993 $uid = $item['contact-uid'];
998 $owner = User::getOwnerDataById($uid);
1000 Logger::info('Fetched activity', ['item' => $item_id, 'uid' => $uid]);
1002 // We don't sign if we aren't the actor. This is important for relaying content especially for forums
1003 if (!$object_mode && !empty($owner) && ($data['actor'] == $owner['url'])) {
1004 return LDSignature::sign($data, $owner);
1009 /// @todo Create "conversation" entry
1013 * Creates a location entry for a given item array
1015 * @param array $item
1017 * @return array with location array
1019 private static function createLocation($item)
1021 $location = ['type' => 'Place'];
1023 if (!empty($item['location'])) {
1024 $location['name'] = $item['location'];
1029 if (empty($item['coord'])) {
1030 $coord = Map::getCoordinates($item['location']);
1032 $coords = explode(' ', $item['coord']);
1033 if (count($coords) == 2) {
1034 $coord = ['lat' => $coords[0], 'lon' => $coords[1]];
1038 if (!empty($coord['lat']) && !empty($coord['lon'])) {
1039 $location['latitude'] = $coord['lat'];
1040 $location['longitude'] = $coord['lon'];
1047 * Returns a tag array for a given item array
1049 * @param array $item
1051 * @return array of tags
1052 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1054 private static function createTagList($item)
1058 $terms = Tag::getByURIId($item['uri-id'], [Tag::HASHTAG, Tag::MENTION, Tag::IMPLICIT_MENTION, Tag::EXCLUSIVE_MENTION]);
1059 foreach ($terms as $term) {
1060 if ($term['type'] == Tag::HASHTAG) {
1061 $url = DI::baseUrl() . '/search?tag=' . urlencode($term['name']);
1062 $tags[] = ['type' => 'Hashtag', 'href' => $url, 'name' => '#' . $term['name']];
1064 $contact = Contact::getByURL($term['url'], false, ['addr']);
1065 if (empty($contact)) {
1068 if (!empty($contact['addr'])) {
1069 $mention = '@' . $contact['addr'];
1071 $mention = '@' . $term['url'];
1074 $tags[] = ['type' => 'Mention', 'href' => $term['url'], 'name' => $mention];
1078 $announce = self::getAnnounceArray($item);
1079 // Mention the original author upon commented reshares
1080 if (!empty($announce['comment'])) {
1081 $tags[] = ['type' => 'Mention', 'href' => $announce['actor']['url'], 'name' => '@' . $announce['actor']['addr']];
1088 * Adds attachment data to the JSON document
1090 * @param array $item Data of the item that is to be posted
1091 * @param string $type Object type
1093 * @return array with attachment data
1094 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1096 private static function createAttachmentList($item, $type)
1100 // Currently deactivated, since it creates side effects on Mastodon and Pleroma.
1101 // It will be reactivated, once this cleared.
1103 $attach_data = BBCode::getAttachmentData($item['body']);
1104 if (!empty($attach_data['url'])) {
1105 $attachment = ['type' => 'Page',
1106 'mediaType' => 'text/html',
1107 'url' => $attach_data['url']];
1109 if (!empty($attach_data['title'])) {
1110 $attachment['name'] = $attach_data['title'];
1113 if (!empty($attach_data['description'])) {
1114 $attachment['summary'] = $attach_data['description'];
1117 if (!empty($attach_data['image'])) {
1118 $imgdata = Images::getInfoFromURLCached($attach_data['image']);
1120 $attachment['icon'] = ['type' => 'Image',
1121 'mediaType' => $imgdata['mime'],
1122 'width' => $imgdata[0],
1123 'height' => $imgdata[1],
1124 'url' => $attach_data['image']];
1128 $attachments[] = $attachment;
1131 $arr = explode('[/attach],', $item['attach']);
1133 foreach ($arr as $r) {
1135 $cnt = preg_match('|\[attach\]href=\"(.*?)\" length=\"(.*?)\" type=\"(.*?)\" title=\"(.*?)\"|', $r, $matches);
1137 $attributes = ['type' => 'Document',
1138 'mediaType' => $matches[3],
1139 'url' => $matches[1],
1142 if (trim($matches[4]) != '') {
1143 $attributes['name'] = trim($matches[4]);
1146 $attachments[] = $attributes;
1151 if ($type != 'Note') {
1152 return $attachments;
1155 // Simplify image codes
1156 $body = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '[img]$3[/img]', $item['body']);
1158 // Grab all pictures without alternative descriptions and create attachments out of them
1159 if (preg_match_all("/\[img\]([^\[\]]*)\[\/img\]/Usi", $body, $pictures)) {
1160 foreach ($pictures[1] as $picture) {
1161 $imgdata = Images::getInfoFromURLCached($picture);
1163 $attachments[] = ['type' => 'Document',
1164 'mediaType' => $imgdata['mime'],
1171 // Grab all pictures with alternative description and create attachments out of them
1172 if (preg_match_all("/\[img=([^\[\]]*)\]([^\[\]]*)\[\/img\]/Usi", $body, $pictures, PREG_SET_ORDER)) {
1173 foreach ($pictures as $picture) {
1174 $imgdata = Images::getInfoFromURLCached($picture[1]);
1176 $attachments[] = ['type' => 'Document',
1177 'mediaType' => $imgdata['mime'],
1178 'url' => $picture[1],
1179 'name' => $picture[2]];
1184 return $attachments;
1188 * Callback function to replace a Friendica style mention in a mention that is used on AP
1190 * @param array $match Matching values for the callback
1191 * @return string Replaced mention
1192 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1194 private static function mentionCallback($match)
1196 if (empty($match[1])) {
1200 $data = Contact::getByURL($match[1], false, ['url', 'nick']);
1201 if (empty($data['nick'])) {
1205 return '@[url=' . $data['url'] . ']' . $data['nick'] . '[/url]';
1209 * Remove image elements since they are added as attachment
1211 * @param string $body
1213 * @return string with removed images
1215 private static function removePictures($body)
1217 // Simplify image codes
1218 $body = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '[img]$3[/img]', $body);
1219 $body = preg_replace("/\[img\=(.*?)\](.*?)\[\/img\]/ism", '[img]$1[/img]', $body);
1221 // Now remove local links
1222 $body = preg_replace_callback(
1223 '/\[url=([^\[\]]*)\]\[img\](.*)\[\/img\]\[\/url\]/Usi',
1225 // We remove the link when it is a link to a local photo page
1226 if (Photo::isLocalPage($match[1])) {
1229 // otherwise we just return the link
1230 return '[url]' . $match[1] . '[/url]';
1235 // Remove all pictures
1236 $body = preg_replace("/\[img\]([^\[\]]*)\[\/img\]/Usi", '', $body);
1242 * Fetches the "context" value for a givem item array from the "conversation" table
1244 * @param array $item
1246 * @return string with context url
1247 * @throws \Exception
1249 private static function fetchContextURLForItem($item)
1251 $conversation = DBA::selectFirst('conversation', ['conversation-href', 'conversation-uri'], ['item-uri' => $item['parent-uri']]);
1252 if (DBA::isResult($conversation) && !empty($conversation['conversation-href'])) {
1253 $context_uri = $conversation['conversation-href'];
1254 } elseif (DBA::isResult($conversation) && !empty($conversation['conversation-uri'])) {
1255 $context_uri = $conversation['conversation-uri'];
1257 $context_uri = $item['parent-uri'] . '#context';
1259 return $context_uri;
1263 * Returns if the post contains sensitive content ("nsfw")
1265 * @param integer $uri_id
1268 * @throws \Exception
1270 private static function isSensitive($uri_id)
1272 return DBA::exists('tag-view', ['uri-id' => $uri_id, 'name' => 'nsfw']);
1276 * Creates event data
1278 * @param array $item
1280 * @return array with the event data
1281 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1283 public static function createEvent($item)
1286 $event['name'] = $item['event-summary'];
1287 $event['content'] = BBCode::convert($item['event-desc'], false, BBCode::ACTIVITYPUB);
1288 $event['startTime'] = DateTimeFormat::utc($item['event-start'] . '+00:00', DateTimeFormat::ATOM);
1290 if (!$item['event-nofinish']) {
1291 $event['endTime'] = DateTimeFormat::utc($item['event-finish'] . '+00:00', DateTimeFormat::ATOM);
1294 if (!empty($item['event-location'])) {
1295 $item['location'] = $item['event-location'];
1296 $event['location'] = self::createLocation($item);
1303 * Creates a note/article object array
1305 * @param array $item
1307 * @return array with the object data
1308 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1309 * @throws \ImagickException
1311 public static function createNote($item)
1317 if ($item['event-type'] == 'event') {
1319 } elseif (!empty($item['title'])) {
1325 if ($item['deleted']) {
1326 $type = 'Tombstone';
1330 $data['id'] = $item['uri'];
1331 $data['type'] = $type;
1333 if ($item['deleted']) {
1337 $data['summary'] = BBCode::toPlaintext(BBCode::getAbstract($item['body'], Protocol::ACTIVITYPUB));
1339 if ($item['uri'] != $item['thr-parent']) {
1340 $data['inReplyTo'] = $item['thr-parent'];
1342 $data['inReplyTo'] = null;
1345 $data['diaspora:guid'] = $item['guid'];
1346 $data['published'] = DateTimeFormat::utc($item['created'] . '+00:00', DateTimeFormat::ATOM);
1348 if ($item['created'] != $item['edited']) {
1349 $data['updated'] = DateTimeFormat::utc($item['edited'] . '+00:00', DateTimeFormat::ATOM);
1352 $data['url'] = $item['plink'];
1353 $data['attributedTo'] = $item['author-link'];
1354 $data['sensitive'] = self::isSensitive($item['uri-id']);
1355 $data['context'] = self::fetchContextURLForItem($item);
1357 if (!empty($item['title'])) {
1358 $data['name'] = BBCode::toPlaintext($item['title'], false);
1361 $permission_block = self::createPermissionBlockForItem($item, false);
1363 $body = $item['body'];
1365 if (empty($item['uid']) || !Feature::isEnabled($item['uid'], 'explicit_mentions')) {
1366 $body = self::prependMentions($body, $item['uri-id']);
1369 if ($type == 'Note') {
1370 $body = self::removePictures($body);
1371 } elseif (($type == 'Article') && empty($data['summary'])) {
1372 $data['summary'] = BBCode::toPlaintext(Plaintext::shorten(self::removePictures($body), 1000));
1375 if ($type == 'Event') {
1376 $data = array_merge($data, self::createEvent($item));
1378 $regexp = "/[@!]\[url\=([^\[\]]*)\].*?\[\/url\]/ism";
1379 $body = preg_replace_callback($regexp, ['self', 'mentionCallback'], $body);
1381 $data['content'] = BBCode::convert($body, false, BBCode::ACTIVITYPUB);
1384 // The regular "content" field does contain a minimized HTML. This is done since systems like
1385 // Mastodon has got problems with - for example - embedded pictures.
1386 // The contentMap does contain the unmodified HTML.
1387 $language = self::getLanguage($item);
1388 if (!empty($language)) {
1389 $regexp = "/[@!]\[url\=([^\[\]]*)\].*?\[\/url\]/ism";
1390 $richbody = preg_replace_callback($regexp, ['self', 'mentionCallback'], $item['body']);
1391 $richbody = BBCode::removeAttachment($richbody);
1393 $data['contentMap'][$language] = BBCode::convert($richbody, false);
1396 $data['source'] = ['content' => $item['body'], 'mediaType' => "text/bbcode"];
1398 if (!empty($item['signed_text']) && ($item['uri'] != $item['thr-parent'])) {
1399 $data['diaspora:comment'] = $item['signed_text'];
1402 $data['attachment'] = self::createAttachmentList($item, $type);
1403 $data['tag'] = self::createTagList($item);
1405 if (empty($data['location']) && (!empty($item['coord']) || !empty($item['location']))) {
1406 $data['location'] = self::createLocation($item);
1409 if (!empty($item['app'])) {
1410 $data['generator'] = ['type' => 'Application', 'name' => $item['app']];
1413 $data = array_merge($data, $permission_block);
1419 * Fetches the language from the post, the user or the system.
1421 * @param array $item
1423 * @return string language string
1425 private static function getLanguage(array $item)
1427 // Try to fetch the language from the post itself
1428 if (!empty($item['language'])) {
1429 $languages = array_keys(json_decode($item['language'], true));
1430 if (!empty($languages[0])) {
1431 return $languages[0];
1435 // Otherwise use the user's language
1436 if (!empty($item['uid'])) {
1437 $user = DBA::selectFirst('user', ['language'], ['uid' => $item['uid']]);
1438 if (!empty($user['language'])) {
1439 return $user['language'];
1443 // And finally just use the system language
1444 return DI::config()->get('system', 'language');
1448 * Creates an an "add tag" entry
1450 * @param array $item
1451 * @param array $data activity data
1453 * @return array with activity data for adding tags
1454 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1455 * @throws \ImagickException
1457 private static function createAddTag($item, $data)
1459 $object = XML::parseString($item['object']);
1460 $target = XML::parseString($item["target"]);
1462 $data['diaspora:guid'] = $item['guid'];
1463 $data['actor'] = $item['author-link'];
1464 $data['target'] = (string)$target->id;
1465 $data['summary'] = BBCode::toPlaintext($item['body']);
1466 $data['object'] = ['id' => (string)$object->id, 'type' => 'tag', 'name' => (string)$object->title, 'content' => (string)$object->content];
1472 * Creates an announce object entry
1474 * @param array $item
1475 * @param array $data activity data
1477 * @return array with activity data
1478 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1479 * @throws \ImagickException
1481 private static function createAnnounce($item, $data)
1483 $orig_body = $item['body'];
1484 $announce = self::getAnnounceArray($item);
1485 if (empty($announce)) {
1486 $data['type'] = 'Create';
1487 $data['object'] = self::createNote($item);
1491 if (empty($announce['comment'])) {
1492 // Pure announce, without a quote
1493 $data['type'] = 'Announce';
1494 $data['object'] = $announce['object']['uri'];
1499 $data['type'] = 'Create';
1500 $item['body'] = $announce['comment'] . "\n" . $announce['object']['plink'];
1501 $data['object'] = self::createNote($item);
1503 /// @todo Finally descide how to implement this in AP. This is a possible way:
1504 $data['object']['attachment'][] = self::createNote($announce['object']);
1506 $data['object']['source']['content'] = $orig_body;
1511 * Return announce related data if the item is an annunce
1513 * @param array $item
1517 public static function getAnnounceArray($item)
1519 $reshared = Item::getShareArray($item);
1520 if (empty($reshared['guid'])) {
1524 $reshared_item = Item::selectFirst([], ['guid' => $reshared['guid']]);
1525 if (!DBA::isResult($reshared_item)) {
1529 if (!in_array($reshared_item['network'], [Protocol::ACTIVITYPUB, Protocol::DFRN])) {
1533 $profile = APContact::getByURL($reshared_item['author-link'], false);
1534 if (empty($profile)) {
1538 return ['object' => $reshared_item, 'actor' => $profile, 'comment' => $reshared['comment']];
1542 * Checks if the provided item array is an announce
1544 * @param array $item
1548 public static function isAnnounce($item)
1550 if ($item['verb'] == Activity::ANNOUNCE) {
1554 $announce = self::getAnnounceArray($item);
1555 if (empty($announce)) {
1559 return empty($announce['comment']);
1563 * Creates an activity id for a given contact id
1565 * @param integer $cid Contact ID of target
1567 * @return bool|string activity id
1569 public static function activityIDFromContact($cid)
1571 $contact = DBA::selectFirst('contact', ['uid', 'id', 'created'], ['id' => $cid]);
1572 if (!DBA::isResult($contact)) {
1576 $hash = hash('ripemd128', $contact['uid'].'-'.$contact['id'].'-'.$contact['created']);
1577 $uuid = substr($hash, 0, 8). '-' . substr($hash, 8, 4) . '-' . substr($hash, 12, 4) . '-' . substr($hash, 16, 4) . '-' . substr($hash, 20, 12);
1578 return DI::baseUrl() . '/activity/' . $uuid;
1582 * Transmits a contact suggestion to a given inbox
1584 * @param integer $uid User ID
1585 * @param string $inbox Target inbox
1586 * @param integer $suggestion_id Suggestion ID
1588 * @return boolean was the transmission successful?
1589 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1591 public static function sendContactSuggestion($uid, $inbox, $suggestion_id)
1593 $owner = User::getOwnerDataById($uid);
1595 $suggestion = DI::fsuggest()->getById($suggestion_id);
1597 $data = ['@context' => ActivityPub::CONTEXT,
1598 'id' => DI::baseUrl() . '/activity/' . System::createGUID(),
1599 'type' => 'Announce',
1600 'actor' => $owner['url'],
1601 'object' => $suggestion->url,
1602 'content' => $suggestion->note,
1603 'instrument' => self::getService(),
1604 'to' => [ActivityPub::PUBLIC_COLLECTION],
1607 $signed = LDSignature::sign($data, $owner);
1609 Logger::log('Deliver profile deletion for user ' . $uid . ' to ' . $inbox . ' via ActivityPub', Logger::DEBUG);
1610 return HTTPSignature::transmit($signed, $inbox, $uid);
1614 * Transmits a profile relocation to a given inbox
1616 * @param integer $uid User ID
1617 * @param string $inbox Target inbox
1619 * @return boolean was the transmission successful?
1620 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1622 public static function sendProfileRelocation($uid, $inbox)
1624 $owner = User::getOwnerDataById($uid);
1626 $data = ['@context' => ActivityPub::CONTEXT,
1627 'id' => DI::baseUrl() . '/activity/' . System::createGUID(),
1628 'type' => 'dfrn:relocate',
1629 'actor' => $owner['url'],
1630 'object' => $owner['url'],
1631 'published' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
1632 'instrument' => self::getService(),
1633 'to' => [ActivityPub::PUBLIC_COLLECTION],
1636 $signed = LDSignature::sign($data, $owner);
1638 Logger::log('Deliver profile relocation for user ' . $uid . ' to ' . $inbox . ' via ActivityPub', Logger::DEBUG);
1639 return HTTPSignature::transmit($signed, $inbox, $uid);
1643 * Transmits a profile deletion to a given inbox
1645 * @param integer $uid User ID
1646 * @param string $inbox Target inbox
1648 * @return boolean was the transmission successful?
1649 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1651 public static function sendProfileDeletion($uid, $inbox)
1653 $owner = User::getOwnerDataById($uid);
1655 if (empty($owner)) {
1656 Logger::error('No owner data found, the deletion message cannot be processed.', ['user' => $uid]);
1660 if (empty($owner['uprvkey'])) {
1661 Logger::error('No private key for owner found, the deletion message cannot be processed.', ['user' => $uid]);
1665 $data = ['@context' => ActivityPub::CONTEXT,
1666 'id' => DI::baseUrl() . '/activity/' . System::createGUID(),
1668 'actor' => $owner['url'],
1669 'object' => $owner['url'],
1670 'published' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
1671 'instrument' => self::getService(),
1672 'to' => [ActivityPub::PUBLIC_COLLECTION],
1675 $signed = LDSignature::sign($data, $owner);
1677 Logger::log('Deliver profile deletion for user ' . $uid . ' to ' . $inbox . ' via ActivityPub', Logger::DEBUG);
1678 return HTTPSignature::transmit($signed, $inbox, $uid);
1682 * Transmits a profile change to a given inbox
1684 * @param integer $uid User ID
1685 * @param string $inbox Target inbox
1687 * @return boolean was the transmission successful?
1688 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1689 * @throws \ImagickException
1691 public static function sendProfileUpdate($uid, $inbox)
1693 $owner = User::getOwnerDataById($uid);
1694 $profile = APContact::getByURL($owner['url']);
1696 $data = ['@context' => ActivityPub::CONTEXT,
1697 'id' => DI::baseUrl() . '/activity/' . System::createGUID(),
1699 'actor' => $owner['url'],
1700 'object' => self::getProfile($uid),
1701 'published' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
1702 'instrument' => self::getService(),
1703 'to' => [$profile['followers']],
1706 $signed = LDSignature::sign($data, $owner);
1708 Logger::log('Deliver profile update for user ' . $uid . ' to ' . $inbox . ' via ActivityPub', Logger::DEBUG);
1709 return HTTPSignature::transmit($signed, $inbox, $uid);
1713 * Transmits a given activity to a target
1715 * @param string $activity Type name
1716 * @param string $target Target profile
1717 * @param integer $uid User ID
1719 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1720 * @throws \ImagickException
1721 * @throws \Exception
1723 public static function sendActivity($activity, $target, $uid, $id = '')
1725 $profile = APContact::getByURL($target);
1726 if (empty($profile['inbox'])) {
1727 Logger::warning('No inbox found for target', ['target' => $target, 'profile' => $profile]);
1731 $owner = User::getOwnerDataById($uid);
1734 $id = DI::baseUrl() . '/activity/' . System::createGUID();
1737 $data = ['@context' => ActivityPub::CONTEXT,
1739 'type' => $activity,
1740 'actor' => $owner['url'],
1741 'object' => $profile['url'],
1742 'instrument' => self::getService(),
1743 'to' => [$profile['url']]];
1745 Logger::log('Sending activity ' . $activity . ' to ' . $target . ' for user ' . $uid, Logger::DEBUG);
1747 $signed = LDSignature::sign($data, $owner);
1748 return HTTPSignature::transmit($signed, $profile['inbox'], $uid);
1752 * Transmits a "follow object" activity to a target
1753 * This is a preparation for sending automated "follow" requests when receiving "Announce" messages
1755 * @param string $object Object URL
1756 * @param string $target Target profile
1757 * @param integer $uid User ID
1759 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1760 * @throws \ImagickException
1761 * @throws \Exception
1763 public static function sendFollowObject($object, $target, $uid = 0)
1765 $profile = APContact::getByURL($target);
1766 if (empty($profile['inbox'])) {
1767 Logger::warning('No inbox found for target', ['target' => $target, 'profile' => $profile]);
1772 // Fetch the list of administrators
1773 $admin_mail = explode(',', str_replace(' ', '', DI::config()->get('config', 'admin_email')));
1775 // We need to use some user as a sender. It doesn't care who it will send. We will use an administrator account.
1776 $condition = ['verified' => true, 'blocked' => false, 'account_removed' => false, 'account_expired' => false, 'email' => $admin_mail];
1777 $first_user = DBA::selectFirst('user', ['uid'], $condition);
1778 $uid = $first_user['uid'];
1781 $condition = ['verb' => Activity::FOLLOW, 'uid' => 0, 'parent-uri' => $object,
1782 'author-id' => Contact::getPublicIdByUserId($uid)];
1783 if (Item::exists($condition)) {
1784 Logger::log('Follow for ' . $object . ' for user ' . $uid . ' does already exist.', Logger::DEBUG);
1788 $owner = User::getOwnerDataById($uid);
1790 $data = ['@context' => ActivityPub::CONTEXT,
1791 'id' => DI::baseUrl() . '/activity/' . System::createGUID(),
1793 'actor' => $owner['url'],
1794 'object' => $object,
1795 'instrument' => self::getService(),
1796 'to' => [$profile['url']]];
1798 Logger::log('Sending follow ' . $object . ' to ' . $target . ' for user ' . $uid, Logger::DEBUG);
1800 $signed = LDSignature::sign($data, $owner);
1801 return HTTPSignature::transmit($signed, $profile['inbox'], $uid);
1805 * Transmit a message that the contact request had been accepted
1807 * @param string $target Target profile
1809 * @param integer $uid User ID
1810 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1811 * @throws \ImagickException
1813 public static function sendContactAccept($target, $id, $uid)
1815 $profile = APContact::getByURL($target);
1816 if (empty($profile['inbox'])) {
1817 Logger::warning('No inbox found for target', ['target' => $target, 'profile' => $profile]);
1821 $owner = User::getOwnerDataById($uid);
1822 $data = ['@context' => ActivityPub::CONTEXT,
1823 'id' => DI::baseUrl() . '/activity/' . System::createGUID(),
1825 'actor' => $owner['url'],
1827 'id' => (string)$id,
1829 'actor' => $profile['url'],
1830 'object' => $owner['url']
1832 'instrument' => self::getService(),
1833 'to' => [$profile['url']]];
1835 Logger::debug('Sending accept to ' . $target . ' for user ' . $uid . ' with id ' . $id);
1837 $signed = LDSignature::sign($data, $owner);
1838 HTTPSignature::transmit($signed, $profile['inbox'], $uid);
1842 * Reject a contact request or terminates the contact relation
1844 * @param string $target Target profile
1846 * @param integer $uid User ID
1847 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1848 * @throws \ImagickException
1850 public static function sendContactReject($target, $id, $uid)
1852 $profile = APContact::getByURL($target);
1853 if (empty($profile['inbox'])) {
1854 Logger::warning('No inbox found for target', ['target' => $target, 'profile' => $profile]);
1858 $owner = User::getOwnerDataById($uid);
1859 $data = ['@context' => ActivityPub::CONTEXT,
1860 'id' => DI::baseUrl() . '/activity/' . System::createGUID(),
1862 'actor' => $owner['url'],
1864 'id' => (string)$id,
1866 'actor' => $profile['url'],
1867 'object' => $owner['url']
1869 'instrument' => self::getService(),
1870 'to' => [$profile['url']]];
1872 Logger::debug('Sending reject to ' . $target . ' for user ' . $uid . ' with id ' . $id);
1874 $signed = LDSignature::sign($data, $owner);
1875 HTTPSignature::transmit($signed, $profile['inbox'], $uid);
1879 * Transmits a message that we don't want to follow this contact anymore
1881 * @param string $target Target profile
1882 * @param integer $uid User ID
1883 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1884 * @throws \ImagickException
1885 * @throws \Exception
1887 public static function sendContactUndo($target, $cid, $uid)
1889 $profile = APContact::getByURL($target);
1890 if (empty($profile['inbox'])) {
1891 Logger::warning('No inbox found for target', ['target' => $target, 'profile' => $profile]);
1895 $object_id = self::activityIDFromContact($cid);
1896 if (empty($object_id)) {
1900 $id = DI::baseUrl() . '/activity/' . System::createGUID();
1902 $owner = User::getOwnerDataById($uid);
1903 $data = ['@context' => ActivityPub::CONTEXT,
1906 'actor' => $owner['url'],
1907 'object' => ['id' => $object_id, 'type' => 'Follow',
1908 'actor' => $owner['url'],
1909 'object' => $profile['url']],
1910 'instrument' => self::getService(),
1911 'to' => [$profile['url']]];
1913 Logger::log('Sending undo to ' . $target . ' for user ' . $uid . ' with id ' . $id, Logger::DEBUG);
1915 $signed = LDSignature::sign($data, $owner);
1916 HTTPSignature::transmit($signed, $profile['inbox'], $uid);
1919 private static function prependMentions($body, int $uriid)
1923 foreach (Tag::getByURIId($uriid, [Tag::IMPLICIT_MENTION]) as $tag) {
1924 $profile = Contact::getByURL($tag['url'], false, ['addr', 'contact-type', 'nick']);
1925 if (!empty($profile['addr'])
1926 && $profile['contact-type'] != Contact::TYPE_COMMUNITY
1927 && !strstr($body, $profile['addr'])
1928 && !strstr($body, $tag['url'])
1930 $mentions[] = '@[url=' . $tag['url'] . ']' . $profile['nick'] . '[/url]';
1934 $mentions[] = $body;
1936 return implode(' ', $mentions);