3 * @file src/Protocol/ActivityPub/Transmitter.php
5 namespace Friendica\Protocol\ActivityPub;
7 use Friendica\Content\Feature;
8 use Friendica\Content\Text\BBCode;
9 use Friendica\Content\Text\Plaintext;
10 use Friendica\Core\Cache;
11 use Friendica\Core\Config;
12 use Friendica\Core\Logger;
13 use Friendica\Core\Protocol;
14 use Friendica\Core\System;
15 use Friendica\Database\DBA;
17 use Friendica\Model\APContact;
18 use Friendica\Model\Contact;
19 use Friendica\Model\Conversation;
20 use Friendica\Model\Item;
21 use Friendica\Model\Profile;
22 use Friendica\Model\Photo;
23 use Friendica\Model\Term;
24 use Friendica\Model\User;
25 use Friendica\Protocol\Activity;
26 use Friendica\Protocol\ActivityPub;
27 use Friendica\Util\DateTimeFormat;
28 use Friendica\Util\HTTPSignature;
29 use Friendica\Util\Images;
30 use Friendica\Util\JsonLD;
31 use Friendica\Util\LDSignature;
32 use Friendica\Util\Map;
33 use Friendica\Util\Network;
34 use Friendica\Util\XML;
36 require_once 'include/api.php';
37 require_once 'mod/share.php';
40 * @brief ActivityPub Transmitter Protocol class
48 * collects the lost of followers of the given owner
50 * @param array $owner Owner array
51 * @param integer $page Page number
53 * @return array of owners
54 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
56 public static function getFollowers($owner, $page = null)
58 $condition = ['rel' => [Contact::FOLLOWER, Contact::FRIEND], 'network' => Protocol::NATIVE_SUPPORT, 'uid' => $owner['uid'],
59 'self' => false, 'deleted' => false, 'hidden' => false, 'archive' => false, 'pending' => false];
60 $count = DBA::count('contact', $condition);
62 $data = ['@context' => ActivityPub::CONTEXT];
63 $data['id'] = DI::baseUrl() . '/followers/' . $owner['nickname'];
64 $data['type'] = 'OrderedCollection';
65 $data['totalItems'] = $count;
67 // When we hide our friends we will only show the pure number but don't allow more.
68 $profile = Profile::getByUID($owner['uid']);
69 if (!empty($profile['hide-friends'])) {
74 $data['first'] = DI::baseUrl() . '/followers/' . $owner['nickname'] . '?page=1';
76 $data['type'] = 'OrderedCollectionPage';
79 $contacts = DBA::select('contact', ['url'], $condition, ['limit' => [($page - 1) * 100, 100]]);
80 while ($contact = DBA::fetch($contacts)) {
81 $list[] = $contact['url'];
85 $data['next'] = DI::baseUrl() . '/followers/' . $owner['nickname'] . '?page=' . ($page + 1);
88 $data['partOf'] = DI::baseUrl() . '/followers/' . $owner['nickname'];
90 $data['orderedItems'] = $list;
97 * Create list of following contacts
99 * @param array $owner Owner array
100 * @param integer $page Page numbe
102 * @return array of following contacts
103 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
105 public static function getFollowing($owner, $page = null)
107 $condition = ['rel' => [Contact::SHARING, Contact::FRIEND], 'network' => Protocol::NATIVE_SUPPORT, 'uid' => $owner['uid'],
108 'self' => false, 'deleted' => false, 'hidden' => false, 'archive' => false, 'pending' => false];
109 $count = DBA::count('contact', $condition);
111 $data = ['@context' => ActivityPub::CONTEXT];
112 $data['id'] = DI::baseUrl() . '/following/' . $owner['nickname'];
113 $data['type'] = 'OrderedCollection';
114 $data['totalItems'] = $count;
116 // When we hide our friends we will only show the pure number but don't allow more.
117 $profile = Profile::getByUID($owner['uid']);
118 if (!empty($profile['hide-friends'])) {
123 $data['first'] = DI::baseUrl() . '/following/' . $owner['nickname'] . '?page=1';
125 $data['type'] = 'OrderedCollectionPage';
128 $contacts = DBA::select('contact', ['url'], $condition, ['limit' => [($page - 1) * 100, 100]]);
129 while ($contact = DBA::fetch($contacts)) {
130 $list[] = $contact['url'];
134 $data['next'] = DI::baseUrl() . '/following/' . $owner['nickname'] . '?page=' . ($page + 1);
137 $data['partOf'] = DI::baseUrl() . '/following/' . $owner['nickname'];
139 $data['orderedItems'] = $list;
146 * Public posts for the given owner
148 * @param array $owner Owner array
149 * @param integer $page Page numbe
151 * @return array of posts
152 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
153 * @throws \ImagickException
155 public static function getOutbox($owner, $page = null)
157 $public_contact = Contact::getIdForURL($owner['url'], 0, true);
159 $condition = ['uid' => 0, 'contact-id' => $public_contact, 'author-id' => $public_contact,
160 'private' => false, 'gravity' => [GRAVITY_PARENT, GRAVITY_COMMENT],
161 'deleted' => false, 'visible' => true, 'moderated' => false];
162 $count = DBA::count('item', $condition);
164 $data = ['@context' => ActivityPub::CONTEXT];
165 $data['id'] = DI::baseUrl() . '/outbox/' . $owner['nickname'];
166 $data['type'] = 'OrderedCollection';
167 $data['totalItems'] = $count;
170 $data['first'] = DI::baseUrl() . '/outbox/' . $owner['nickname'] . '?page=1';
172 $data['type'] = 'OrderedCollectionPage';
175 $condition['parent-network'] = Protocol::NATIVE_SUPPORT;
177 $items = Item::select(['id'], $condition, ['limit' => [($page - 1) * 20, 20], 'order' => ['created' => true]]);
178 while ($item = Item::fetch($items)) {
179 $activity = self::createActivityFromItem($item['id'], true);
180 // Only list "Create" activity objects here, no reshares
181 if (is_array($activity['object']) && ($activity['type'] == 'Create')) {
182 $list[] = $activity['object'];
187 $data['next'] = DI::baseUrl() . '/outbox/' . $owner['nickname'] . '?page=' . ($page + 1);
190 $data['partOf'] = DI::baseUrl() . '/outbox/' . $owner['nickname'];
192 $data['orderedItems'] = $list;
199 * Return the service array containing information the used software and it's url
201 * @return array with service data
203 private static function getService()
205 return ['type' => 'Service',
206 'name' => FRIENDICA_PLATFORM . " '" . FRIENDICA_CODENAME . "' " . FRIENDICA_VERSION . '-' . DB_UPDATE_VERSION,
207 'url' => DI::baseUrl()->get()];
211 * Return the ActivityPub profile of the given user
213 * @param integer $uid User ID
214 * @return array with profile data
215 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
217 public static function getProfile($uid)
219 $condition = ['uid' => $uid, 'blocked' => false, 'account_expired' => false,
220 'account_removed' => false, 'verified' => true];
221 $fields = ['guid', 'nickname', 'pubkey', 'account-type', 'page-flags'];
222 $user = DBA::selectFirst('user', $fields, $condition);
223 if (!DBA::isResult($user)) {
227 $fields = ['locality', 'region', 'country-name'];
228 $profile = DBA::selectFirst('profile', $fields, ['uid' => $uid, 'is-default' => true]);
229 if (!DBA::isResult($profile)) {
233 $fields = ['name', 'url', 'location', 'about', 'avatar', 'photo'];
234 $contact = DBA::selectFirst('contact', $fields, ['uid' => $uid, 'self' => true]);
235 if (!DBA::isResult($contact)) {
239 $data = ['@context' => ActivityPub::CONTEXT];
240 $data['id'] = $contact['url'];
241 $data['diaspora:guid'] = $user['guid'];
242 $data['type'] = ActivityPub::ACCOUNT_TYPES[$user['account-type']];
243 $data['following'] = DI::baseUrl() . '/following/' . $user['nickname'];
244 $data['followers'] = DI::baseUrl() . '/followers/' . $user['nickname'];
245 $data['inbox'] = DI::baseUrl() . '/inbox/' . $user['nickname'];
246 $data['outbox'] = DI::baseUrl() . '/outbox/' . $user['nickname'];
247 $data['preferredUsername'] = $user['nickname'];
248 $data['name'] = $contact['name'];
249 $data['vcard:hasAddress'] = ['@type' => 'vcard:Home', 'vcard:country-name' => $profile['country-name'],
250 'vcard:region' => $profile['region'], 'vcard:locality' => $profile['locality']];
251 $data['summary'] = $contact['about'];
252 $data['url'] = $contact['url'];
253 $data['manuallyApprovesFollowers'] = in_array($user['page-flags'], [User::PAGE_FLAGS_NORMAL, User::PAGE_FLAGS_PRVGROUP]);
254 $data['publicKey'] = ['id' => $contact['url'] . '#main-key',
255 'owner' => $contact['url'],
256 'publicKeyPem' => $user['pubkey']];
257 $data['endpoints'] = ['sharedInbox' => DI::baseUrl() . '/inbox'];
258 $data['icon'] = ['type' => 'Image',
259 'url' => $contact['photo']];
261 $data['generator'] = self::getService();
263 // tags: https://kitty.town/@inmysocks/100656097926961126.json
268 * @param string $username
270 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
272 public static function getDeletedUser($username)
275 '@context' => ActivityPub::CONTEXT,
276 'id' => DI::baseUrl() . '/profile/' . $username,
277 'type' => 'Tombstone',
278 'published' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
279 'updated' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
280 'deleted' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
285 * Returns an array with permissions of a given item array
289 * @return array with permissions
290 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
291 * @throws \ImagickException
293 private static function fetchPermissionBlockFromConversation($item)
295 if (empty($item['thr-parent'])) {
299 $condition = ['item-uri' => $item['thr-parent'], 'protocol' => Conversation::PARCEL_ACTIVITYPUB];
300 $conversation = DBA::selectFirst('conversation', ['source'], $condition);
301 if (!DBA::isResult($conversation)) {
305 $activity = json_decode($conversation['source'], true);
307 $actor = JsonLD::fetchElement($activity, 'actor', 'id');
308 $profile = APContact::getByURL($actor);
310 $item_profile = APContact::getByURL($item['author-link']);
311 $exclude[] = $item['author-link'];
313 if ($item['gravity'] == GRAVITY_PARENT) {
314 $exclude[] = $item['owner-link'];
317 $permissions['to'][] = $actor;
319 foreach (['to', 'cc', 'bto', 'bcc'] as $element) {
320 if (empty($activity[$element])) {
323 if (is_string($activity[$element])) {
324 $activity[$element] = [$activity[$element]];
327 foreach ($activity[$element] as $receiver) {
328 if ($receiver == $profile['followers'] && !empty($item_profile['followers'])) {
329 $permissions[$element][] = $item_profile['followers'];
330 } elseif (!in_array($receiver, $exclude)) {
331 $permissions[$element][] = $receiver;
339 * Creates an array of permissions from an item thread
341 * @param array $item Item array
342 * @param boolean $blindcopy addressing via "bcc" or "cc"?
343 * @param integer $last_id Last item id for adding receivers
344 * @param boolean $forum_mode "true" means that we are sending content to a forum
346 * @return array with permission data
347 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
348 * @throws \ImagickException
350 private static function createPermissionBlockForItem($item, $blindcopy, $last_id = 0, $forum_mode = false)
353 $last_id = $item['id'];
358 // Check if we should always deliver our stuff via BCC
359 if (!empty($item['uid'])) {
360 $profile = Profile::getByUID($item['uid']);
361 if (!empty($profile)) {
362 $always_bcc = $profile['hide-friends'];
366 if (Config::get('system', 'ap_always_bcc')) {
370 if (self::isAnnounce($item) || Config::get('debug', 'total_ap_delivery')) {
371 // Will be activated in a later step
372 $networks = Protocol::FEDERATED;
374 // For now only send to these contacts:
375 $networks = [Protocol::ACTIVITYPUB, Protocol::OSTATUS];
378 $data = ['to' => [], 'cc' => [], 'bcc' => []];
380 if ($item['gravity'] == GRAVITY_PARENT) {
381 $actor_profile = APContact::getByURL($item['owner-link']);
383 $actor_profile = APContact::getByURL($item['author-link']);
386 $terms = Term::tagArrayFromItemId($item['id'], [Term::MENTION, Term::IMPLICIT_MENTION]);
388 if (!$item['private']) {
389 // Directly mention the original author upon a quoted reshare.
390 // Else just ensure that the original author receives the reshare.
391 $announce = self::getAnnounceArray($item);
392 if (!empty($announce['comment'])) {
393 $data['to'][] = $announce['actor']['url'];
394 } elseif (!empty($announce)) {
395 $data['cc'][] = $announce['actor']['url'];
398 $data = array_merge($data, self::fetchPermissionBlockFromConversation($item));
400 $data['to'][] = ActivityPub::PUBLIC_COLLECTION;
402 foreach ($terms as $term) {
403 $profile = APContact::getByURL($term['url'], false);
404 if (!empty($profile)) {
405 $data['to'][] = $profile['url'];
409 $receiver_list = Item::enumeratePermissions($item, true);
411 foreach ($terms as $term) {
412 $cid = Contact::getIdForURL($term['url'], $item['uid']);
413 if (!empty($cid) && in_array($cid, $receiver_list)) {
414 $contact = DBA::selectFirst('contact', ['url', 'network', 'protocol'], ['id' => $cid]);
415 if (!DBA::isResult($contact) || (!in_array($contact['network'], $networks) && ($contact['protocol'] != Protocol::ACTIVITYPUB))) {
419 if (!empty($profile = APContact::getByURL($contact['url'], false))) {
420 $data['to'][] = $profile['url'];
425 foreach ($receiver_list as $receiver) {
426 $contact = DBA::selectFirst('contact', ['url', 'hidden', 'network', 'protocol'], ['id' => $receiver]);
427 if (!DBA::isResult($contact) || (!in_array($contact['network'], $networks) && ($contact['protocol'] != Protocol::ACTIVITYPUB))) {
431 if (!empty($profile = APContact::getByURL($contact['url'], false))) {
432 if ($contact['hidden'] || $always_bcc) {
433 $data['bcc'][] = $profile['url'];
435 $data['cc'][] = $profile['url'];
441 if (!empty($item['parent'])) {
442 $parents = Item::select(['id', 'author-link', 'owner-link', 'gravity', 'uri'], ['parent' => $item['parent']]);
443 while ($parent = Item::fetch($parents)) {
444 if ($parent['gravity'] == GRAVITY_PARENT) {
445 $profile = APContact::getByURL($parent['owner-link'], false);
446 if (!empty($profile)) {
447 if ($item['gravity'] != GRAVITY_PARENT) {
448 // Comments to forums are directed to the forum
449 // But comments to forums aren't directed to the followers collection
450 if ($profile['type'] == 'Group') {
451 $data['to'][] = $profile['url'];
453 $data['cc'][] = $profile['url'];
454 if (!$item['private'] && !empty($actor_profile['followers'])) {
455 $data['cc'][] = $actor_profile['followers'];
459 // Public thread parent post always are directed to the followers
460 if (!$item['private'] && !$forum_mode) {
461 $data['cc'][] = $actor_profile['followers'];
467 // Don't include data from future posts
468 if ($parent['id'] >= $last_id) {
472 $profile = APContact::getByURL($parent['author-link'], false);
473 if (!empty($profile)) {
474 if (($profile['type'] == 'Group') || ($parent['uri'] == $item['thr-parent'])) {
475 $data['to'][] = $profile['url'];
477 $data['cc'][] = $profile['url'];
481 DBA::close($parents);
484 $data['to'] = array_unique($data['to']);
485 $data['cc'] = array_unique($data['cc']);
486 $data['bcc'] = array_unique($data['bcc']);
488 if (($key = array_search($item['author-link'], $data['to'])) !== false) {
489 unset($data['to'][$key]);
492 if (($key = array_search($item['author-link'], $data['cc'])) !== false) {
493 unset($data['cc'][$key]);
496 if (($key = array_search($item['author-link'], $data['bcc'])) !== false) {
497 unset($data['bcc'][$key]);
500 foreach ($data['to'] as $to) {
501 if (($key = array_search($to, $data['cc'])) !== false) {
502 unset($data['cc'][$key]);
505 if (($key = array_search($to, $data['bcc'])) !== false) {
506 unset($data['bcc'][$key]);
510 foreach ($data['cc'] as $cc) {
511 if (($key = array_search($cc, $data['bcc'])) !== false) {
512 unset($data['bcc'][$key]);
516 $receivers = ['to' => array_values($data['to']), 'cc' => array_values($data['cc']), 'bcc' => array_values($data['bcc'])];
519 unset($receivers['bcc']);
526 * Check if an inbox is archived
528 * @param string $url Inbox url
530 * @return boolean "true" if inbox is archived
532 private static function archivedInbox($url)
534 return DBA::exists('inbox-status', ['url' => $url, 'archive' => true]);
538 * Fetches a list of inboxes of followers of a given user
540 * @param integer $uid User ID
541 * @param boolean $personal fetch personal inboxes
543 * @return array of follower inboxes
544 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
545 * @throws \ImagickException
547 public static function fetchTargetInboxesforUser($uid, $personal = false)
551 if (Config::get('debug', 'total_ap_delivery')) {
552 // Will be activated in a later step
553 $networks = Protocol::FEDERATED;
555 // For now only send to these contacts:
556 $networks = [Protocol::ACTIVITYPUB, Protocol::OSTATUS];
559 $condition = ['uid' => $uid, 'archive' => false, 'pending' => false];
562 $condition['rel'] = [Contact::FOLLOWER, Contact::FRIEND];
565 $contacts = DBA::select('contact', ['url', 'network', 'protocol'], $condition);
566 while ($contact = DBA::fetch($contacts)) {
567 if (Contact::isLocal($contact['url'])) {
571 if (!in_array($contact['network'], $networks) && ($contact['protocol'] != Protocol::ACTIVITYPUB)) {
575 if (Network::isUrlBlocked($contact['url'])) {
579 $profile = APContact::getByURL($contact['url'], false);
580 if (!empty($profile)) {
581 if (empty($profile['sharedinbox']) || $personal) {
582 $target = $profile['inbox'];
584 $target = $profile['sharedinbox'];
586 if (!self::archivedInbox($target)) {
587 $inboxes[$target] = $target;
591 DBA::close($contacts);
597 * Fetches an array of inboxes for the given item and user
599 * @param array $item Item array
600 * @param integer $uid User ID
601 * @param boolean $personal fetch personal inboxes
602 * @param integer $last_id Last item id for adding receivers
603 * @param boolean $forum_mode "true" means that we are sending content to a forum
604 * @return array with inboxes
605 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
606 * @throws \ImagickException
608 public static function fetchTargetInboxes($item, $uid, $personal = false, $last_id = 0, $forum_mode = false)
610 $permissions = self::createPermissionBlockForItem($item, true, $last_id, $forum_mode);
611 if (empty($permissions)) {
617 if ($item['gravity'] == GRAVITY_ACTIVITY) {
618 $item_profile = APContact::getByURL($item['author-link'], false);
620 $item_profile = APContact::getByURL($item['owner-link'], false);
623 foreach (['to', 'cc', 'bto', 'bcc'] as $element) {
624 if (empty($permissions[$element])) {
628 $blindcopy = in_array($element, ['bto', 'bcc']);
630 foreach ($permissions[$element] as $receiver) {
631 if (Network::isUrlBlocked($receiver)) {
635 if ($receiver == $item_profile['followers']) {
636 $inboxes = array_merge($inboxes, self::fetchTargetInboxesforUser($uid, $personal));
638 if (Contact::isLocal($receiver)) {
642 $profile = APContact::getByURL($receiver, false);
643 if (!empty($profile)) {
644 if (empty($profile['sharedinbox']) || $personal || $blindcopy) {
645 $target = $profile['inbox'];
647 $target = $profile['sharedinbox'];
649 if (!self::archivedInbox($target)) {
650 $inboxes[$target] = $target;
661 * Creates an array in the structure of the item table for a given mail id
663 * @param integer $mail_id
668 public static function ItemArrayFromMail($mail_id)
670 $mail = DBA::selectFirst('mail', [], ['id' => $mail_id]);
671 if (!DBA::isResult($mail)) {
675 $reply = DBA::selectFirst('mail', ['uri'], ['parent-uri' => $mail['parent-uri'], 'reply' => false]);
677 // Making the post more compatible for Mastodon by:
678 // - Making it a note and not an article (no title)
679 // - Moving the title into the "summary" field that is used as a "content warning"
680 $mail['body'] = '[abstract]' . $mail['title'] . "[/abstract]\n" . $mail['body'];
683 $mail['author-link'] = $mail['owner-link'] = $mail['from-url'];
684 $mail['allow_cid'] = '<'.$mail['contact-id'].'>';
685 $mail['allow_gid'] = '';
686 $mail['deny_cid'] = '';
687 $mail['deny_gid'] = '';
688 $mail['private'] = true;
689 $mail['deleted'] = false;
690 $mail['edited'] = $mail['created'];
691 $mail['plink'] = $mail['uri'];
692 $mail['thr-parent'] = $reply['uri'];
693 $mail['gravity'] = ($mail['reply'] ? GRAVITY_COMMENT: GRAVITY_PARENT);
695 $mail['event-type'] = '';
696 $mail['attach'] = '';
704 * Creates an activity array for a given mail id
706 * @param integer $mail_id
707 * @param boolean $object_mode Is the activity item is used inside another object?
709 * @return array of activity
712 public static function createActivityFromMail($mail_id, $object_mode = false)
714 $mail = self::ItemArrayFromMail($mail_id);
715 $object = self::createNote($mail);
718 $data = ['@context' => ActivityPub::CONTEXT];
723 $data['id'] = $mail['uri'] . '#Create';
724 $data['type'] = 'Create';
725 $data['actor'] = $mail['author-link'];
726 $data['published'] = DateTimeFormat::utc($mail['created'] . '+00:00', DateTimeFormat::ATOM);
727 $data['instrument'] = self::getService();
728 $data = array_merge($data, self::createPermissionBlockForItem($mail, true));
730 if (empty($data['to']) && !empty($data['cc'])) {
731 $data['to'] = $data['cc'];
734 if (empty($data['to']) && !empty($data['bcc'])) {
735 $data['to'] = $data['bcc'];
741 $object['to'] = $data['to'];
742 $object['tag'] = [['type' => 'Mention', 'href' => $object['to'][0], 'name' => '']];
744 unset($object['cc']);
745 unset($object['bcc']);
747 $data['directMessage'] = true;
749 $data['object'] = $object;
751 $owner = User::getOwnerDataById($mail['uid']);
753 if (!$object_mode && !empty($owner)) {
754 return LDSignature::sign($data, $owner);
761 * Returns the activity type of a given item
765 * @return string with activity type
766 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
767 * @throws \ImagickException
769 private static function getTypeOfItem($item)
773 // Only check for a reshare, if it is a real reshare and no quoted reshare
774 if (strpos($item['body'], "[share") === 0) {
775 $announce = self::getAnnounceArray($item);
776 $reshared = !empty($announce);
781 } elseif ($item['verb'] == Activity::POST) {
782 if ($item['created'] == $item['edited']) {
787 } elseif ($item['verb'] == Activity::LIKE) {
789 } elseif ($item['verb'] == Activity::DISLIKE) {
791 } elseif ($item['verb'] == Activity::ATTEND) {
793 } elseif ($item['verb'] == Activity::ATTENDNO) {
795 } elseif ($item['verb'] == Activity::ATTENDMAYBE) {
796 $type = 'TentativeAccept';
797 } elseif ($item['verb'] == Activity::FOLLOW) {
799 } elseif ($item['verb'] == Activity::TAG) {
809 * Creates the activity or fetches it from the cache
811 * @param integer $item_id
812 * @param boolean $force Force new cache entry
814 * @return array with the activity
817 public static function createCachedActivityFromItem($item_id, $force = false)
819 $cachekey = 'APDelivery:createActivity:' . $item_id;
822 $data = Cache::get($cachekey);
823 if (!is_null($data)) {
828 $data = ActivityPub\Transmitter::createActivityFromItem($item_id);
830 Cache::set($cachekey, $data, Cache::QUARTER_HOUR);
835 * Creates an activity array for a given item id
837 * @param integer $item_id
838 * @param boolean $object_mode Is the activity item is used inside another object?
840 * @return array of activity
843 public static function createActivityFromItem($item_id, $object_mode = false)
845 $item = Item::selectFirst([], ['id' => $item_id, 'parent-network' => Protocol::NATIVE_SUPPORT]);
847 if (!DBA::isResult($item)) {
851 if ($item['wall'] && ($item['uri'] == $item['parent-uri'])) {
852 $owner = User::getOwnerDataById($item['uid']);
853 if (($owner['account-type'] == User::ACCOUNT_TYPE_COMMUNITY) && ($item['author-link'] != $owner['url'])) {
856 // Disguise forum posts as reshares. Will later be converted to a real announce
857 $item['body'] = share_header($item['author-name'], $item['author-link'], $item['author-avatar'],
858 $item['guid'], $item['created'], $item['plink']) . $item['body'] . '[/share]';
863 $condition = ['item-uri' => $item['uri'], 'protocol' => Conversation::PARCEL_ACTIVITYPUB];
864 $conversation = DBA::selectFirst('conversation', ['source'], $condition);
865 if (DBA::isResult($conversation)) {
866 $data = json_decode($conversation['source'], true);
872 $type = self::getTypeOfItem($item);
876 $data = ['@context' => ActivityPub::CONTEXT];
878 if ($item['deleted'] && ($item['gravity'] == GRAVITY_ACTIVITY)) {
880 } elseif ($item['deleted']) {
887 $data['id'] = $item['uri'] . '#' . $type;
888 $data['type'] = $type;
890 if (Item::isForumPost($item) && ($type != 'Announce')) {
891 $data['actor'] = $item['author-link'];
893 $data['actor'] = $item['owner-link'];
896 $data['published'] = DateTimeFormat::utc($item['created'] . '+00:00', DateTimeFormat::ATOM);
898 $data['instrument'] = self::getService();
900 $data = array_merge($data, self::createPermissionBlockForItem($item, false));
902 if (in_array($data['type'], ['Create', 'Update', 'Delete'])) {
903 $data['object'] = self::createNote($item);
904 } elseif ($data['type'] == 'Add') {
905 $data = self::createAddTag($item, $data);
906 } elseif ($data['type'] == 'Announce') {
907 $data = self::createAnnounce($item, $data);
908 } elseif ($data['type'] == 'Follow') {
909 $data['object'] = $item['parent-uri'];
910 } elseif ($data['type'] == 'Undo') {
911 $data['object'] = self::createActivityFromItem($item_id, true);
913 $data['diaspora:guid'] = $item['guid'];
914 if (!empty($item['signed_text'])) {
915 $data['diaspora:like'] = $item['signed_text'];
917 $data['object'] = $item['thr-parent'];
920 if (!empty($item['contact-uid'])) {
921 $uid = $item['contact-uid'];
926 $owner = User::getOwnerDataById($uid);
928 if (!$object_mode && !empty($owner)) {
929 return LDSignature::sign($data, $owner);
934 /// @todo Create "conversation" entry
938 * Creates a location entry for a given item array
942 * @return array with location array
944 private static function createLocation($item)
946 $location = ['type' => 'Place'];
948 if (!empty($item['location'])) {
949 $location['name'] = $item['location'];
954 if (empty($item['coord'])) {
955 $coord = Map::getCoordinates($item['location']);
957 $coords = explode(' ', $item['coord']);
958 if (count($coords) == 2) {
959 $coord = ['lat' => $coords[0], 'lon' => $coords[1]];
963 if (!empty($coord['lat']) && !empty($coord['lon'])) {
964 $location['latitude'] = $coord['lat'];
965 $location['longitude'] = $coord['lon'];
972 * Returns a tag array for a given item array
976 * @return array of tags
977 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
979 private static function createTagList($item)
983 $terms = Term::tagArrayFromItemId($item['id'], [Term::HASHTAG, Term::MENTION, Term::IMPLICIT_MENTION]);
984 foreach ($terms as $term) {
985 if ($term['type'] == Term::HASHTAG) {
986 $url = DI::baseUrl() . '/search?tag=' . urlencode($term['term']);
987 $tags[] = ['type' => 'Hashtag', 'href' => $url, 'name' => '#' . $term['term']];
988 } elseif ($term['type'] == Term::MENTION || $term['type'] == Term::IMPLICIT_MENTION) {
989 $contact = Contact::getDetailsByURL($term['url']);
990 if (!empty($contact['addr'])) {
991 $mention = '@' . $contact['addr'];
993 $mention = '@' . $term['url'];
996 $tags[] = ['type' => 'Mention', 'href' => $term['url'], 'name' => $mention];
1000 $announce = self::getAnnounceArray($item);
1001 // Mention the original author upon commented reshares
1002 if (!empty($announce['comment'])) {
1003 $tags[] = ['type' => 'Mention', 'href' => $announce['actor']['url'], 'name' => '@' . $announce['actor']['addr']];
1010 * Adds attachment data to the JSON document
1012 * @param array $item Data of the item that is to be posted
1013 * @param string $type Object type
1015 * @return array with attachment data
1016 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1018 private static function createAttachmentList($item, $type)
1022 // Currently deactivated, since it creates side effects on Mastodon and Pleroma.
1023 // It will be reactivated, once this cleared.
1025 $attach_data = BBCode::getAttachmentData($item['body']);
1026 if (!empty($attach_data['url'])) {
1027 $attachment = ['type' => 'Page',
1028 'mediaType' => 'text/html',
1029 'url' => $attach_data['url']];
1031 if (!empty($attach_data['title'])) {
1032 $attachment['name'] = $attach_data['title'];
1035 if (!empty($attach_data['description'])) {
1036 $attachment['summary'] = $attach_data['description'];
1039 if (!empty($attach_data['image'])) {
1040 $imgdata = Images::getInfoFromURLCached($attach_data['image']);
1042 $attachment['icon'] = ['type' => 'Image',
1043 'mediaType' => $imgdata['mime'],
1044 'width' => $imgdata[0],
1045 'height' => $imgdata[1],
1046 'url' => $attach_data['image']];
1050 $attachments[] = $attachment;
1053 $arr = explode('[/attach],', $item['attach']);
1055 foreach ($arr as $r) {
1057 $cnt = preg_match('|\[attach\]href=\"(.*?)\" length=\"(.*?)\" type=\"(.*?)\" title=\"(.*?)\"|', $r, $matches);
1059 $attributes = ['type' => 'Document',
1060 'mediaType' => $matches[3],
1061 'url' => $matches[1],
1064 if (trim($matches[4]) != '') {
1065 $attributes['name'] = trim($matches[4]);
1068 $attachments[] = $attributes;
1073 if ($type != 'Note') {
1074 return $attachments;
1077 // Simplify image codes
1078 $body = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '[img]$3[/img]', $item['body']);
1080 // Grab all pictures without alternative descriptions and create attachments out of them
1081 if (preg_match_all("/\[img\]([^\[\]]*)\[\/img\]/Usi", $body, $pictures)) {
1082 foreach ($pictures[1] as $picture) {
1083 $imgdata = Images::getInfoFromURLCached($picture);
1085 $attachments[] = ['type' => 'Document',
1086 'mediaType' => $imgdata['mime'],
1093 // Grab all pictures with alternative description and create attachments out of them
1094 if (preg_match_all("/\[img=([^\[\]]*)\]([^\[\]]*)\[\/img\]/Usi", $body, $pictures, PREG_SET_ORDER)) {
1095 foreach ($pictures as $picture) {
1096 $imgdata = Images::getInfoFromURLCached($picture[1]);
1098 $attachments[] = ['type' => 'Document',
1099 'mediaType' => $imgdata['mime'],
1100 'url' => $picture[1],
1101 'name' => $picture[2]];
1106 return $attachments;
1110 * @brief Callback function to replace a Friendica style mention in a mention that is used on AP
1112 * @param array $match Matching values for the callback
1113 * @return string Replaced mention
1114 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1116 private static function mentionCallback($match)
1118 if (empty($match[1])) {
1122 $data = Contact::getDetailsByURL($match[1]);
1123 if (empty($data['nick'])) {
1127 return '@[url=' . $data['url'] . ']' . $data['nick'] . '[/url]';
1131 * Remove image elements since they are added as attachment
1133 * @param string $body
1135 * @return string with removed images
1137 private static function removePictures($body)
1139 // Simplify image codes
1140 $body = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '[img]$3[/img]', $body);
1141 $body = preg_replace("/\[img\=(.*?)\](.*?)\[\/img\]/ism", '[img]$1[/img]', $body);
1143 // Now remove local links
1144 $body = preg_replace_callback(
1145 '/\[url=([^\[\]]*)\]\[img\](.*)\[\/img\]\[\/url\]/Usi',
1147 // We remove the link when it is a link to a local photo page
1148 if (Photo::isLocalPage($match[1])) {
1151 // otherwise we just return the link
1152 return '[url]' . $match[1] . '[/url]';
1157 // Remove all pictures
1158 $body = preg_replace("/\[img\]([^\[\]]*)\[\/img\]/Usi", '', $body);
1164 * Fetches the "context" value for a givem item array from the "conversation" table
1166 * @param array $item
1168 * @return string with context url
1169 * @throws \Exception
1171 private static function fetchContextURLForItem($item)
1173 $conversation = DBA::selectFirst('conversation', ['conversation-href', 'conversation-uri'], ['item-uri' => $item['parent-uri']]);
1174 if (DBA::isResult($conversation) && !empty($conversation['conversation-href'])) {
1175 $context_uri = $conversation['conversation-href'];
1176 } elseif (DBA::isResult($conversation) && !empty($conversation['conversation-uri'])) {
1177 $context_uri = $conversation['conversation-uri'];
1179 $context_uri = $item['parent-uri'] . '#context';
1181 return $context_uri;
1185 * Returns if the post contains sensitive content ("nsfw")
1187 * @param integer $item_id
1190 * @throws \Exception
1192 private static function isSensitive($item_id)
1194 $condition = ['otype' => TERM_OBJ_POST, 'oid' => $item_id, 'type' => TERM_HASHTAG, 'term' => 'nsfw'];
1195 return DBA::exists('term', $condition);
1199 * Creates event data
1201 * @param array $item
1203 * @return array with the event data
1204 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1206 public static function createEvent($item)
1209 $event['name'] = $item['event-summary'];
1210 $event['content'] = BBCode::convert($item['event-desc'], false, 9);
1211 $event['startTime'] = DateTimeFormat::utc($item['event-start'] . '+00:00', DateTimeFormat::ATOM);
1213 if (!$item['event-nofinish']) {
1214 $event['endTime'] = DateTimeFormat::utc($item['event-finish'] . '+00:00', DateTimeFormat::ATOM);
1217 if (!empty($item['event-location'])) {
1218 $item['location'] = $item['event-location'];
1219 $event['location'] = self::createLocation($item);
1226 * Creates a note/article object array
1228 * @param array $item
1230 * @return array with the object data
1231 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1232 * @throws \ImagickException
1234 public static function createNote($item)
1240 if ($item['event-type'] == 'event') {
1242 } elseif (!empty($item['title'])) {
1248 if ($item['deleted']) {
1249 $type = 'Tombstone';
1253 $data['id'] = $item['uri'];
1254 $data['type'] = $type;
1256 if ($item['deleted']) {
1260 $data['summary'] = BBCode::toPlaintext(BBCode::getAbstract($item['body'], Protocol::ACTIVITYPUB));
1262 if ($item['uri'] != $item['thr-parent']) {
1263 $data['inReplyTo'] = $item['thr-parent'];
1265 $data['inReplyTo'] = null;
1268 $data['diaspora:guid'] = $item['guid'];
1269 $data['published'] = DateTimeFormat::utc($item['created'] . '+00:00', DateTimeFormat::ATOM);
1271 if ($item['created'] != $item['edited']) {
1272 $data['updated'] = DateTimeFormat::utc($item['edited'] . '+00:00', DateTimeFormat::ATOM);
1275 $data['url'] = $item['plink'];
1276 $data['attributedTo'] = $item['author-link'];
1277 $data['sensitive'] = self::isSensitive($item['id']);
1278 $data['context'] = self::fetchContextURLForItem($item);
1280 if (!empty($item['title'])) {
1281 $data['name'] = BBCode::toPlaintext($item['title'], false);
1284 $permission_block = self::createPermissionBlockForItem($item, false);
1286 $body = $item['body'];
1288 if (empty($item['uid']) || !Feature::isEnabled($item['uid'], 'explicit_mentions')) {
1289 $body = self::prependMentions($body, $permission_block);
1292 if ($type == 'Note') {
1293 $body = self::removePictures($body);
1294 } elseif (($type == 'Article') && empty($data['summary'])) {
1295 $data['summary'] = BBCode::toPlaintext(Plaintext::shorten(self::removePictures($body), 1000));
1298 if ($type == 'Event') {
1299 $data = array_merge($data, self::createEvent($item));
1301 $regexp = "/[@!]\[url\=([^\[\]]*)\].*?\[\/url\]/ism";
1302 $body = preg_replace_callback($regexp, ['self', 'mentionCallback'], $body);
1304 $data['content'] = BBCode::convert($body, false, 9);
1307 $regexp = "/[@!]\[url\=([^\[\]]*)\].*?\[\/url\]/ism";
1308 $richbody = preg_replace_callback($regexp, ['self', 'mentionCallback'], $item['body']);
1309 $richbody = BBCode::removeAttachment($richbody);
1311 $data['contentMap']['text/html'] = BBCode::convert($richbody, false);
1312 $data['contentMap']['text/markdown'] = BBCode::toMarkdown($item["body"]);
1314 $data['source'] = ['content' => $item['body'], 'mediaType' => "text/bbcode"];
1316 if (!empty($item['signed_text']) && ($item['uri'] != $item['thr-parent'])) {
1317 $data['diaspora:comment'] = $item['signed_text'];
1320 $data['attachment'] = self::createAttachmentList($item, $type);
1321 $data['tag'] = self::createTagList($item);
1323 if (empty($data['location']) && (!empty($item['coord']) || !empty($item['location']))) {
1324 $data['location'] = self::createLocation($item);
1327 if (!empty($item['app'])) {
1328 $data['generator'] = ['type' => 'Application', 'name' => $item['app']];
1331 $data = array_merge($data, $permission_block);
1337 * Creates an an "add tag" entry
1339 * @param array $item
1340 * @param array $data activity data
1342 * @return array with activity data for adding tags
1343 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1344 * @throws \ImagickException
1346 private static function createAddTag($item, $data)
1348 $object = XML::parseString($item['object'], false);
1349 $target = XML::parseString($item["target"], false);
1351 $data['diaspora:guid'] = $item['guid'];
1352 $data['actor'] = $item['author-link'];
1353 $data['target'] = (string)$target->id;
1354 $data['summary'] = BBCode::toPlaintext($item['body']);
1355 $data['object'] = ['id' => (string)$object->id, 'type' => 'tag', 'name' => (string)$object->title, 'content' => (string)$object->content];
1361 * Creates an announce object entry
1363 * @param array $item
1364 * @param array $data activity data
1366 * @return array with activity data
1367 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1368 * @throws \ImagickException
1370 private static function createAnnounce($item, $data)
1372 $orig_body = $item['body'];
1373 $announce = self::getAnnounceArray($item);
1374 if (empty($announce)) {
1375 $data['type'] = 'Create';
1376 $data['object'] = self::createNote($item);
1380 if (empty($announce['comment'])) {
1381 // Pure announce, without a quote
1382 $data['type'] = 'Announce';
1383 $data['object'] = $announce['object']['uri'];
1388 $data['type'] = 'Create';
1389 $item['body'] = $announce['comment'] . "\n" . $announce['object']['plink'];
1390 $data['object'] = self::createNote($item);
1392 /// @todo Finally descide how to implement this in AP. This is a possible way:
1393 $data['object']['attachment'][] = self::createNote($announce['object']);
1395 $data['object']['source']['content'] = $orig_body;
1400 * Return announce related data if the item is an annunce
1402 * @param array $item
1406 public static function getAnnounceArray($item)
1408 $reshared = Item::getShareArray($item);
1409 if (empty($reshared['guid'])) {
1413 $reshared_item = Item::selectFirst([], ['guid' => $reshared['guid']]);
1414 if (!DBA::isResult($reshared_item)) {
1418 if (!in_array($reshared_item['network'], [Protocol::ACTIVITYPUB, Protocol::DFRN])) {
1422 $profile = APContact::getByURL($reshared_item['author-link'], false);
1423 if (empty($profile)) {
1427 return ['object' => $reshared_item, 'actor' => $profile, 'comment' => $reshared['comment']];
1431 * Checks if the provided item array is an announce
1433 * @param array $item
1437 public static function isAnnounce($item)
1439 $announce = self::getAnnounceArray($item);
1440 if (empty($announce)) {
1444 return empty($announce['comment']);
1448 * Creates an activity id for a given contact id
1450 * @param integer $cid Contact ID of target
1452 * @return bool|string activity id
1454 public static function activityIDFromContact($cid)
1456 $contact = DBA::selectFirst('contact', ['uid', 'id', 'created'], ['id' => $cid]);
1457 if (!DBA::isResult($contact)) {
1461 $hash = hash('ripemd128', $contact['uid'].'-'.$contact['id'].'-'.$contact['created']);
1462 $uuid = substr($hash, 0, 8). '-' . substr($hash, 8, 4) . '-' . substr($hash, 12, 4) . '-' . substr($hash, 16, 4) . '-' . substr($hash, 20, 12);
1463 return DI::baseUrl() . '/activity/' . $uuid;
1467 * Transmits a contact suggestion to a given inbox
1469 * @param integer $uid User ID
1470 * @param string $inbox Target inbox
1471 * @param integer $suggestion_id Suggestion ID
1473 * @return boolean was the transmission successful?
1474 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1476 public static function sendContactSuggestion($uid, $inbox, $suggestion_id)
1478 $owner = User::getOwnerDataById($uid);
1480 $suggestion = DBA::selectFirst('fsuggest', ['url', 'note', 'created'], ['id' => $suggestion_id]);
1482 $data = ['@context' => ActivityPub::CONTEXT,
1483 'id' => DI::baseUrl() . '/activity/' . System::createGUID(),
1484 'type' => 'Announce',
1485 'actor' => $owner['url'],
1486 'object' => $suggestion['url'],
1487 'content' => $suggestion['note'],
1488 'instrument' => self::getService(),
1489 'to' => [ActivityPub::PUBLIC_COLLECTION],
1492 $signed = LDSignature::sign($data, $owner);
1494 Logger::log('Deliver profile deletion for user ' . $uid . ' to ' . $inbox . ' via ActivityPub', Logger::DEBUG);
1495 return HTTPSignature::transmit($signed, $inbox, $uid);
1499 * Transmits a profile relocation to a given inbox
1501 * @param integer $uid User ID
1502 * @param string $inbox Target inbox
1504 * @return boolean was the transmission successful?
1505 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1507 public static function sendProfileRelocation($uid, $inbox)
1509 $owner = User::getOwnerDataById($uid);
1511 $data = ['@context' => ActivityPub::CONTEXT,
1512 'id' => DI::baseUrl() . '/activity/' . System::createGUID(),
1513 'type' => 'dfrn:relocate',
1514 'actor' => $owner['url'],
1515 'object' => $owner['url'],
1516 'published' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
1517 'instrument' => self::getService(),
1518 'to' => [ActivityPub::PUBLIC_COLLECTION],
1521 $signed = LDSignature::sign($data, $owner);
1523 Logger::log('Deliver profile relocation for user ' . $uid . ' to ' . $inbox . ' via ActivityPub', Logger::DEBUG);
1524 return HTTPSignature::transmit($signed, $inbox, $uid);
1528 * Transmits a profile deletion to a given inbox
1530 * @param integer $uid User ID
1531 * @param string $inbox Target inbox
1533 * @return boolean was the transmission successful?
1534 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1536 public static function sendProfileDeletion($uid, $inbox)
1538 $owner = User::getOwnerDataById($uid);
1540 if (empty($owner)) {
1541 Logger::error('No owner data found, the deletion message cannot be processed.', ['user' => $uid]);
1545 if (empty($owner['uprvkey'])) {
1546 Logger::error('No private key for owner found, the deletion message cannot be processed.', ['user' => $uid]);
1550 $data = ['@context' => ActivityPub::CONTEXT,
1551 'id' => DI::baseUrl() . '/activity/' . System::createGUID(),
1553 'actor' => $owner['url'],
1554 'object' => $owner['url'],
1555 'published' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
1556 'instrument' => self::getService(),
1557 'to' => [ActivityPub::PUBLIC_COLLECTION],
1560 $signed = LDSignature::sign($data, $owner);
1562 Logger::log('Deliver profile deletion for user ' . $uid . ' to ' . $inbox . ' via ActivityPub', Logger::DEBUG);
1563 return HTTPSignature::transmit($signed, $inbox, $uid);
1567 * Transmits a profile change to a given inbox
1569 * @param integer $uid User ID
1570 * @param string $inbox Target inbox
1572 * @return boolean was the transmission successful?
1573 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1574 * @throws \ImagickException
1576 public static function sendProfileUpdate($uid, $inbox)
1578 $owner = User::getOwnerDataById($uid);
1579 $profile = APContact::getByURL($owner['url']);
1581 $data = ['@context' => ActivityPub::CONTEXT,
1582 'id' => DI::baseUrl() . '/activity/' . System::createGUID(),
1584 'actor' => $owner['url'],
1585 'object' => self::getProfile($uid),
1586 'published' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
1587 'instrument' => self::getService(),
1588 'to' => [$profile['followers']],
1591 $signed = LDSignature::sign($data, $owner);
1593 Logger::log('Deliver profile update for user ' . $uid . ' to ' . $inbox . ' via ActivityPub', Logger::DEBUG);
1594 return HTTPSignature::transmit($signed, $inbox, $uid);
1598 * Transmits a given activity to a target
1600 * @param string $activity Type name
1601 * @param string $target Target profile
1602 * @param integer $uid User ID
1604 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1605 * @throws \ImagickException
1606 * @throws \Exception
1608 public static function sendActivity($activity, $target, $uid, $id = '')
1610 $profile = APContact::getByURL($target);
1611 if (empty($profile['inbox'])) {
1612 Logger::warning('No inbox found for target', ['target' => $target, 'profile' => $profile]);
1616 $owner = User::getOwnerDataById($uid);
1619 $id = DI::baseUrl() . '/activity/' . System::createGUID();
1622 $data = ['@context' => ActivityPub::CONTEXT,
1624 'type' => $activity,
1625 'actor' => $owner['url'],
1626 'object' => $profile['url'],
1627 'instrument' => self::getService(),
1628 'to' => [$profile['url']]];
1630 Logger::log('Sending activity ' . $activity . ' to ' . $target . ' for user ' . $uid, Logger::DEBUG);
1632 $signed = LDSignature::sign($data, $owner);
1633 return HTTPSignature::transmit($signed, $profile['inbox'], $uid);
1637 * Transmits a "follow object" activity to a target
1638 * This is a preparation for sending automated "follow" requests when receiving "Announce" messages
1640 * @param string $object Object URL
1641 * @param string $target Target profile
1642 * @param integer $uid User ID
1644 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1645 * @throws \ImagickException
1646 * @throws \Exception
1648 public static function sendFollowObject($object, $target, $uid = 0)
1650 $profile = APContact::getByURL($target);
1651 if (empty($profile['inbox'])) {
1652 Logger::warning('No inbox found for target', ['target' => $target, 'profile' => $profile]);
1657 // Fetch the list of administrators
1658 $admin_mail = explode(',', str_replace(' ', '', Config::get('config', 'admin_email')));
1660 // We need to use some user as a sender. It doesn't care who it will send. We will use an administrator account.
1661 $condition = ['verified' => true, 'blocked' => false, 'account_removed' => false, 'account_expired' => false, 'email' => $admin_mail];
1662 $first_user = DBA::selectFirst('user', ['uid'], $condition);
1663 $uid = $first_user['uid'];
1666 $condition = ['verb' => Activity::FOLLOW, 'uid' => 0, 'parent-uri' => $object,
1667 'author-id' => Contact::getPublicIdByUserId($uid)];
1668 if (Item::exists($condition)) {
1669 Logger::log('Follow for ' . $object . ' for user ' . $uid . ' does already exist.', Logger::DEBUG);
1673 $owner = User::getOwnerDataById($uid);
1675 $data = ['@context' => ActivityPub::CONTEXT,
1676 'id' => DI::baseUrl() . '/activity/' . System::createGUID(),
1678 'actor' => $owner['url'],
1679 'object' => $object,
1680 'instrument' => self::getService(),
1681 'to' => [$profile['url']]];
1683 Logger::log('Sending follow ' . $object . ' to ' . $target . ' for user ' . $uid, Logger::DEBUG);
1685 $signed = LDSignature::sign($data, $owner);
1686 return HTTPSignature::transmit($signed, $profile['inbox'], $uid);
1690 * Transmit a message that the contact request had been accepted
1692 * @param string $target Target profile
1694 * @param integer $uid User ID
1695 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1696 * @throws \ImagickException
1698 public static function sendContactAccept($target, $id, $uid)
1700 $profile = APContact::getByURL($target);
1701 if (empty($profile['inbox'])) {
1702 Logger::warning('No inbox found for target', ['target' => $target, 'profile' => $profile]);
1706 $owner = User::getOwnerDataById($uid);
1707 $data = ['@context' => ActivityPub::CONTEXT,
1708 'id' => DI::baseUrl() . '/activity/' . System::createGUID(),
1710 'actor' => $owner['url'],
1712 'id' => (string)$id,
1714 'actor' => $profile['url'],
1715 'object' => $owner['url']
1717 'instrument' => self::getService(),
1718 'to' => [$profile['url']]];
1720 Logger::debug('Sending accept to ' . $target . ' for user ' . $uid . ' with id ' . $id);
1722 $signed = LDSignature::sign($data, $owner);
1723 HTTPSignature::transmit($signed, $profile['inbox'], $uid);
1727 * Reject a contact request or terminates the contact relation
1729 * @param string $target Target profile
1731 * @param integer $uid User ID
1732 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1733 * @throws \ImagickException
1735 public static function sendContactReject($target, $id, $uid)
1737 $profile = APContact::getByURL($target);
1738 if (empty($profile['inbox'])) {
1739 Logger::warning('No inbox found for target', ['target' => $target, 'profile' => $profile]);
1743 $owner = User::getOwnerDataById($uid);
1744 $data = ['@context' => ActivityPub::CONTEXT,
1745 'id' => DI::baseUrl() . '/activity/' . System::createGUID(),
1747 'actor' => $owner['url'],
1749 'id' => (string)$id,
1751 'actor' => $profile['url'],
1752 'object' => $owner['url']
1754 'instrument' => self::getService(),
1755 'to' => [$profile['url']]];
1757 Logger::debug('Sending reject to ' . $target . ' for user ' . $uid . ' with id ' . $id);
1759 $signed = LDSignature::sign($data, $owner);
1760 HTTPSignature::transmit($signed, $profile['inbox'], $uid);
1764 * Transmits a message that we don't want to follow this contact anymore
1766 * @param string $target Target profile
1767 * @param integer $uid User ID
1768 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1769 * @throws \ImagickException
1770 * @throws \Exception
1772 public static function sendContactUndo($target, $cid, $uid)
1774 $profile = APContact::getByURL($target);
1775 if (empty($profile['inbox'])) {
1776 Logger::warning('No inbox found for target', ['target' => $target, 'profile' => $profile]);
1780 $object_id = self::activityIDFromContact($cid);
1781 if (empty($object_id)) {
1785 $id = DI::baseUrl() . '/activity/' . System::createGUID();
1787 $owner = User::getOwnerDataById($uid);
1788 $data = ['@context' => ActivityPub::CONTEXT,
1791 'actor' => $owner['url'],
1792 'object' => ['id' => $object_id, 'type' => 'Follow',
1793 'actor' => $owner['url'],
1794 'object' => $profile['url']],
1795 'instrument' => self::getService(),
1796 'to' => [$profile['url']]];
1798 Logger::log('Sending undo to ' . $target . ' for user ' . $uid . ' with id ' . $id, Logger::DEBUG);
1800 $signed = LDSignature::sign($data, $owner);
1801 HTTPSignature::transmit($signed, $profile['inbox'], $uid);
1804 private static function prependMentions($body, array $permission_block)
1806 if (Config::get('system', 'disable_implicit_mentions')) {
1812 foreach ($permission_block['to'] as $profile_url) {
1813 $profile = Contact::getDetailsByURL($profile_url);
1814 if (!empty($profile['addr'])
1815 && $profile['contact-type'] != Contact::TYPE_COMMUNITY
1816 && !strstr($body, $profile['addr'])
1817 && !strstr($body, $profile_url)
1819 $mentions[] = '@[url=' . $profile_url . ']' . $profile['nick'] . '[/url]';
1823 $mentions[] = $body;
1825 return implode(' ', $mentions);