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\Duration;
11 use Friendica\Core\Logger;
12 use Friendica\Core\Protocol;
13 use Friendica\Core\System;
14 use Friendica\Database\DBA;
16 use Friendica\Model\APContact;
17 use Friendica\Model\Contact;
18 use Friendica\Model\Conversation;
19 use Friendica\Model\Item;
20 use Friendica\Model\Profile;
21 use Friendica\Model\Photo;
22 use Friendica\Model\Term;
23 use Friendica\Model\User;
24 use Friendica\Protocol\Activity;
25 use Friendica\Protocol\ActivityPub;
26 use Friendica\Util\DateTimeFormat;
27 use Friendica\Util\HTTPSignature;
28 use Friendica\Util\Images;
29 use Friendica\Util\JsonLD;
30 use Friendica\Util\LDSignature;
31 use Friendica\Util\Map;
32 use Friendica\Util\Network;
33 use Friendica\Util\XML;
35 require_once 'include/api.php';
36 require_once 'mod/share.php';
39 * ActivityPub Transmitter Protocol class
47 * collects the lost of followers of the given owner
49 * @param array $owner Owner array
50 * @param integer $page Page number
52 * @return array of owners
53 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
55 public static function getFollowers($owner, $page = null)
57 $condition = ['rel' => [Contact::FOLLOWER, Contact::FRIEND], 'network' => Protocol::NATIVE_SUPPORT, 'uid' => $owner['uid'],
58 'self' => false, 'deleted' => false, 'hidden' => false, 'archive' => false, 'pending' => false];
59 $count = DBA::count('contact', $condition);
61 $data = ['@context' => ActivityPub::CONTEXT];
62 $data['id'] = DI::baseUrl() . '/followers/' . $owner['nickname'];
63 $data['type'] = 'OrderedCollection';
64 $data['totalItems'] = $count;
66 // When we hide our friends we will only show the pure number but don't allow more.
67 $profile = Profile::getByUID($owner['uid']);
68 if (!empty($profile['hide-friends'])) {
73 $data['first'] = DI::baseUrl() . '/followers/' . $owner['nickname'] . '?page=1';
75 $data['type'] = 'OrderedCollectionPage';
78 $contacts = DBA::select('contact', ['url'], $condition, ['limit' => [($page - 1) * 100, 100]]);
79 while ($contact = DBA::fetch($contacts)) {
80 $list[] = $contact['url'];
84 $data['next'] = DI::baseUrl() . '/followers/' . $owner['nickname'] . '?page=' . ($page + 1);
87 $data['partOf'] = DI::baseUrl() . '/followers/' . $owner['nickname'];
89 $data['orderedItems'] = $list;
96 * Create list of following contacts
98 * @param array $owner Owner array
99 * @param integer $page Page numbe
101 * @return array of following contacts
102 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
104 public static function getFollowing($owner, $page = null)
106 $condition = ['rel' => [Contact::SHARING, Contact::FRIEND], 'network' => Protocol::NATIVE_SUPPORT, 'uid' => $owner['uid'],
107 'self' => false, 'deleted' => false, 'hidden' => false, 'archive' => false, 'pending' => false];
108 $count = DBA::count('contact', $condition);
110 $data = ['@context' => ActivityPub::CONTEXT];
111 $data['id'] = DI::baseUrl() . '/following/' . $owner['nickname'];
112 $data['type'] = 'OrderedCollection';
113 $data['totalItems'] = $count;
115 // When we hide our friends we will only show the pure number but don't allow more.
116 $profile = Profile::getByUID($owner['uid']);
117 if (!empty($profile['hide-friends'])) {
122 $data['first'] = DI::baseUrl() . '/following/' . $owner['nickname'] . '?page=1';
124 $data['type'] = 'OrderedCollectionPage';
127 $contacts = DBA::select('contact', ['url'], $condition, ['limit' => [($page - 1) * 100, 100]]);
128 while ($contact = DBA::fetch($contacts)) {
129 $list[] = $contact['url'];
133 $data['next'] = DI::baseUrl() . '/following/' . $owner['nickname'] . '?page=' . ($page + 1);
136 $data['partOf'] = DI::baseUrl() . '/following/' . $owner['nickname'];
138 $data['orderedItems'] = $list;
145 * Public posts for the given owner
147 * @param array $owner Owner array
148 * @param integer $page Page numbe
150 * @return array of posts
151 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
152 * @throws \ImagickException
154 public static function getOutbox($owner, $page = null)
156 $public_contact = Contact::getIdForURL($owner['url'], 0, true);
158 $condition = ['uid' => 0, 'contact-id' => $public_contact, 'author-id' => $public_contact,
159 'private' => false, 'gravity' => [GRAVITY_PARENT, GRAVITY_COMMENT],
160 'deleted' => false, 'visible' => true, 'moderated' => false];
161 $count = DBA::count('item', $condition);
163 $data = ['@context' => ActivityPub::CONTEXT];
164 $data['id'] = DI::baseUrl() . '/outbox/' . $owner['nickname'];
165 $data['type'] = 'OrderedCollection';
166 $data['totalItems'] = $count;
169 $data['first'] = DI::baseUrl() . '/outbox/' . $owner['nickname'] . '?page=1';
171 $data['type'] = 'OrderedCollectionPage';
174 $condition['parent-network'] = Protocol::NATIVE_SUPPORT;
176 $items = Item::select(['id'], $condition, ['limit' => [($page - 1) * 20, 20], 'order' => ['created' => true]]);
177 while ($item = Item::fetch($items)) {
178 $activity = self::createActivityFromItem($item['id'], true);
179 // Only list "Create" activity objects here, no reshares
180 if (is_array($activity['object']) && ($activity['type'] == 'Create')) {
181 $list[] = $activity['object'];
186 $data['next'] = DI::baseUrl() . '/outbox/' . $owner['nickname'] . '?page=' . ($page + 1);
189 $data['partOf'] = DI::baseUrl() . '/outbox/' . $owner['nickname'];
191 $data['orderedItems'] = $list;
198 * Return the service array containing information the used software and it's url
200 * @return array with service data
202 private static function getService()
204 return ['type' => 'Service',
205 'name' => FRIENDICA_PLATFORM . " '" . FRIENDICA_CODENAME . "' " . FRIENDICA_VERSION . '-' . DB_UPDATE_VERSION,
206 'url' => DI::baseUrl()->get()];
210 * Return the ActivityPub profile of the given user
212 * @param integer $uid User ID
213 * @return array with profile data
214 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
216 public static function getProfile($uid)
218 $condition = ['uid' => $uid, 'blocked' => false, 'account_expired' => false,
219 'account_removed' => false, 'verified' => true];
220 $fields = ['guid', 'nickname', 'pubkey', 'account-type', 'page-flags'];
221 $user = DBA::selectFirst('user', $fields, $condition);
222 if (!DBA::isResult($user)) {
226 $fields = ['locality', 'region', 'country-name'];
227 $profile = DBA::selectFirst('profile', $fields, ['uid' => $uid, 'is-default' => true]);
228 if (!DBA::isResult($profile)) {
232 $fields = ['name', 'url', 'location', 'about', 'avatar', 'photo'];
233 $contact = DBA::selectFirst('contact', $fields, ['uid' => $uid, 'self' => true]);
234 if (!DBA::isResult($contact)) {
238 $data = ['@context' => ActivityPub::CONTEXT];
239 $data['id'] = $contact['url'];
240 $data['diaspora:guid'] = $user['guid'];
241 $data['type'] = ActivityPub::ACCOUNT_TYPES[$user['account-type']];
242 $data['following'] = DI::baseUrl() . '/following/' . $user['nickname'];
243 $data['followers'] = DI::baseUrl() . '/followers/' . $user['nickname'];
244 $data['inbox'] = DI::baseUrl() . '/inbox/' . $user['nickname'];
245 $data['outbox'] = DI::baseUrl() . '/outbox/' . $user['nickname'];
246 $data['preferredUsername'] = $user['nickname'];
247 $data['name'] = $contact['name'];
248 $data['vcard:hasAddress'] = ['@type' => 'vcard:Home', 'vcard:country-name' => $profile['country-name'],
249 'vcard:region' => $profile['region'], 'vcard:locality' => $profile['locality']];
250 $data['summary'] = $contact['about'];
251 $data['url'] = $contact['url'];
252 $data['manuallyApprovesFollowers'] = in_array($user['page-flags'], [User::PAGE_FLAGS_NORMAL, User::PAGE_FLAGS_PRVGROUP]);
253 $data['publicKey'] = ['id' => $contact['url'] . '#main-key',
254 'owner' => $contact['url'],
255 'publicKeyPem' => $user['pubkey']];
256 $data['endpoints'] = ['sharedInbox' => DI::baseUrl() . '/inbox'];
257 $data['icon'] = ['type' => 'Image',
258 'url' => $contact['photo']];
260 $data['generator'] = self::getService();
262 // tags: https://kitty.town/@inmysocks/100656097926961126.json
267 * @param string $username
269 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
271 public static function getDeletedUser($username)
274 '@context' => ActivityPub::CONTEXT,
275 'id' => DI::baseUrl() . '/profile/' . $username,
276 'type' => 'Tombstone',
277 'published' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
278 'updated' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
279 'deleted' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
284 * Returns an array with permissions of a given item array
288 * @return array with permissions
289 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
290 * @throws \ImagickException
292 private static function fetchPermissionBlockFromConversation($item)
294 if (empty($item['thr-parent'])) {
298 $condition = ['item-uri' => $item['thr-parent'], 'protocol' => Conversation::PARCEL_ACTIVITYPUB];
299 $conversation = DBA::selectFirst('conversation', ['source'], $condition);
300 if (!DBA::isResult($conversation)) {
304 $activity = json_decode($conversation['source'], true);
306 $actor = JsonLD::fetchElement($activity, 'actor', 'id');
307 $profile = APContact::getByURL($actor);
309 $item_profile = APContact::getByURL($item['author-link']);
310 $exclude[] = $item['author-link'];
312 if ($item['gravity'] == GRAVITY_PARENT) {
313 $exclude[] = $item['owner-link'];
316 $permissions['to'][] = $actor;
318 foreach (['to', 'cc', 'bto', 'bcc'] as $element) {
319 if (empty($activity[$element])) {
322 if (is_string($activity[$element])) {
323 $activity[$element] = [$activity[$element]];
326 foreach ($activity[$element] as $receiver) {
327 if ($receiver == $profile['followers'] && !empty($item_profile['followers'])) {
328 $permissions[$element][] = $item_profile['followers'];
329 } elseif (!in_array($receiver, $exclude)) {
330 $permissions[$element][] = $receiver;
338 * Creates an array of permissions from an item thread
340 * @param array $item Item array
341 * @param boolean $blindcopy addressing via "bcc" or "cc"?
342 * @param integer $last_id Last item id for adding receivers
343 * @param boolean $forum_mode "true" means that we are sending content to a forum
345 * @return array with permission data
346 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
347 * @throws \ImagickException
349 private static function createPermissionBlockForItem($item, $blindcopy, $last_id = 0, $forum_mode = false)
352 $last_id = $item['id'];
357 // Check if we should always deliver our stuff via BCC
358 if (!empty($item['uid'])) {
359 $profile = Profile::getByUID($item['uid']);
360 if (!empty($profile)) {
361 $always_bcc = $profile['hide-friends'];
365 if (DI::config()->get('system', 'ap_always_bcc')) {
369 if (self::isAnnounce($item) || DI::config()->get('debug', 'total_ap_delivery')) {
370 // Will be activated in a later step
371 $networks = Protocol::FEDERATED;
373 // For now only send to these contacts:
374 $networks = [Protocol::ACTIVITYPUB, Protocol::OSTATUS];
377 $data = ['to' => [], 'cc' => [], 'bcc' => []];
379 if ($item['gravity'] == GRAVITY_PARENT) {
380 $actor_profile = APContact::getByURL($item['owner-link']);
382 $actor_profile = APContact::getByURL($item['author-link']);
385 $terms = Term::tagArrayFromItemId($item['id'], [Term::MENTION, Term::IMPLICIT_MENTION]);
387 if (!$item['private']) {
388 // Directly mention the original author upon a quoted reshare.
389 // Else just ensure that the original author receives the reshare.
390 $announce = self::getAnnounceArray($item);
391 if (!empty($announce['comment'])) {
392 $data['to'][] = $announce['actor']['url'];
393 } elseif (!empty($announce)) {
394 $data['cc'][] = $announce['actor']['url'];
397 $data = array_merge($data, self::fetchPermissionBlockFromConversation($item));
399 $data['to'][] = ActivityPub::PUBLIC_COLLECTION;
401 foreach ($terms as $term) {
402 $profile = APContact::getByURL($term['url'], false);
403 if (!empty($profile)) {
404 $data['to'][] = $profile['url'];
408 $receiver_list = Item::enumeratePermissions($item, true);
410 foreach ($terms as $term) {
411 $cid = Contact::getIdForURL($term['url'], $item['uid']);
412 if (!empty($cid) && in_array($cid, $receiver_list)) {
413 $contact = DBA::selectFirst('contact', ['url', 'network', 'protocol'], ['id' => $cid]);
414 if (!DBA::isResult($contact) || (!in_array($contact['network'], $networks) && ($contact['protocol'] != Protocol::ACTIVITYPUB))) {
418 if (!empty($profile = APContact::getByURL($contact['url'], false))) {
419 $data['to'][] = $profile['url'];
424 foreach ($receiver_list as $receiver) {
425 $contact = DBA::selectFirst('contact', ['url', 'hidden', 'network', 'protocol'], ['id' => $receiver]);
426 if (!DBA::isResult($contact) || (!in_array($contact['network'], $networks) && ($contact['protocol'] != Protocol::ACTIVITYPUB))) {
430 if (!empty($profile = APContact::getByURL($contact['url'], false))) {
431 if ($contact['hidden'] || $always_bcc) {
432 $data['bcc'][] = $profile['url'];
434 $data['cc'][] = $profile['url'];
440 if (!empty($item['parent'])) {
441 $parents = Item::select(['id', 'author-link', 'owner-link', 'gravity', 'uri'], ['parent' => $item['parent']]);
442 while ($parent = Item::fetch($parents)) {
443 if ($parent['gravity'] == GRAVITY_PARENT) {
444 $profile = APContact::getByURL($parent['owner-link'], false);
445 if (!empty($profile)) {
446 if ($item['gravity'] != GRAVITY_PARENT) {
447 // Comments to forums are directed to the forum
448 // But comments to forums aren't directed to the followers collection
449 if ($profile['type'] == 'Group') {
450 $data['to'][] = $profile['url'];
452 $data['cc'][] = $profile['url'];
453 if (!$item['private'] && !empty($actor_profile['followers'])) {
454 $data['cc'][] = $actor_profile['followers'];
458 // Public thread parent post always are directed to the followers
459 if (!$item['private'] && !$forum_mode) {
460 $data['cc'][] = $actor_profile['followers'];
466 // Don't include data from future posts
467 if ($parent['id'] >= $last_id) {
471 $profile = APContact::getByURL($parent['author-link'], false);
472 if (!empty($profile)) {
473 if (($profile['type'] == 'Group') || ($parent['uri'] == $item['thr-parent'])) {
474 $data['to'][] = $profile['url'];
476 $data['cc'][] = $profile['url'];
480 DBA::close($parents);
483 $data['to'] = array_unique($data['to']);
484 $data['cc'] = array_unique($data['cc']);
485 $data['bcc'] = array_unique($data['bcc']);
487 if (($key = array_search($item['author-link'], $data['to'])) !== false) {
488 unset($data['to'][$key]);
491 if (($key = array_search($item['author-link'], $data['cc'])) !== false) {
492 unset($data['cc'][$key]);
495 if (($key = array_search($item['author-link'], $data['bcc'])) !== false) {
496 unset($data['bcc'][$key]);
499 foreach ($data['to'] as $to) {
500 if (($key = array_search($to, $data['cc'])) !== false) {
501 unset($data['cc'][$key]);
504 if (($key = array_search($to, $data['bcc'])) !== false) {
505 unset($data['bcc'][$key]);
509 foreach ($data['cc'] as $cc) {
510 if (($key = array_search($cc, $data['bcc'])) !== false) {
511 unset($data['bcc'][$key]);
515 $receivers = ['to' => array_values($data['to']), 'cc' => array_values($data['cc']), 'bcc' => array_values($data['bcc'])];
518 unset($receivers['bcc']);
525 * Check if an inbox is archived
527 * @param string $url Inbox url
529 * @return boolean "true" if inbox is archived
531 private static function archivedInbox($url)
533 return DBA::exists('inbox-status', ['url' => $url, 'archive' => true]);
537 * Fetches a list of inboxes of followers of a given user
539 * @param integer $uid User ID
540 * @param boolean $personal fetch personal inboxes
542 * @return array of follower inboxes
543 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
544 * @throws \ImagickException
546 public static function fetchTargetInboxesforUser($uid, $personal = false)
550 if (DI::config()->get('debug', 'total_ap_delivery')) {
551 // Will be activated in a later step
552 $networks = Protocol::FEDERATED;
554 // For now only send to these contacts:
555 $networks = [Protocol::ACTIVITYPUB, Protocol::OSTATUS];
558 $condition = ['uid' => $uid, 'archive' => false, 'pending' => false];
561 $condition['rel'] = [Contact::FOLLOWER, Contact::FRIEND];
564 $contacts = DBA::select('contact', ['url', 'network', 'protocol'], $condition);
565 while ($contact = DBA::fetch($contacts)) {
566 if (Contact::isLocal($contact['url'])) {
570 if (!in_array($contact['network'], $networks) && ($contact['protocol'] != Protocol::ACTIVITYPUB)) {
574 if (Network::isUrlBlocked($contact['url'])) {
578 $profile = APContact::getByURL($contact['url'], false);
579 if (!empty($profile)) {
580 if (empty($profile['sharedinbox']) || $personal) {
581 $target = $profile['inbox'];
583 $target = $profile['sharedinbox'];
585 if (!self::archivedInbox($target)) {
586 $inboxes[$target] = $target;
590 DBA::close($contacts);
596 * Fetches an array of inboxes for the given item and user
598 * @param array $item Item array
599 * @param integer $uid User ID
600 * @param boolean $personal fetch personal inboxes
601 * @param integer $last_id Last item id for adding receivers
602 * @param boolean $forum_mode "true" means that we are sending content to a forum
603 * @return array with inboxes
604 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
605 * @throws \ImagickException
607 public static function fetchTargetInboxes($item, $uid, $personal = false, $last_id = 0, $forum_mode = false)
609 $permissions = self::createPermissionBlockForItem($item, true, $last_id, $forum_mode);
610 if (empty($permissions)) {
616 if ($item['gravity'] == GRAVITY_ACTIVITY) {
617 $item_profile = APContact::getByURL($item['author-link'], false);
619 $item_profile = APContact::getByURL($item['owner-link'], false);
622 foreach (['to', 'cc', 'bto', 'bcc'] as $element) {
623 if (empty($permissions[$element])) {
627 $blindcopy = in_array($element, ['bto', 'bcc']);
629 foreach ($permissions[$element] as $receiver) {
630 if (Network::isUrlBlocked($receiver)) {
634 if ($receiver == $item_profile['followers']) {
635 $inboxes = array_merge($inboxes, self::fetchTargetInboxesforUser($uid, $personal));
637 if (Contact::isLocal($receiver)) {
641 $profile = APContact::getByURL($receiver, false);
642 if (!empty($profile)) {
643 if (empty($profile['sharedinbox']) || $personal || $blindcopy) {
644 $target = $profile['inbox'];
646 $target = $profile['sharedinbox'];
648 if (!self::archivedInbox($target)) {
649 $inboxes[$target] = $target;
660 * Creates an array in the structure of the item table for a given mail id
662 * @param integer $mail_id
667 public static function ItemArrayFromMail($mail_id)
669 $mail = DBA::selectFirst('mail', [], ['id' => $mail_id]);
670 if (!DBA::isResult($mail)) {
674 $reply = DBA::selectFirst('mail', ['uri'], ['parent-uri' => $mail['parent-uri'], 'reply' => false]);
676 // Making the post more compatible for Mastodon by:
677 // - Making it a note and not an article (no title)
678 // - Moving the title into the "summary" field that is used as a "content warning"
679 $mail['body'] = '[abstract]' . $mail['title'] . "[/abstract]\n" . $mail['body'];
682 $mail['author-link'] = $mail['owner-link'] = $mail['from-url'];
683 $mail['allow_cid'] = '<'.$mail['contact-id'].'>';
684 $mail['allow_gid'] = '';
685 $mail['deny_cid'] = '';
686 $mail['deny_gid'] = '';
687 $mail['private'] = true;
688 $mail['deleted'] = false;
689 $mail['edited'] = $mail['created'];
690 $mail['plink'] = $mail['uri'];
691 $mail['thr-parent'] = $reply['uri'];
692 $mail['gravity'] = ($mail['reply'] ? GRAVITY_COMMENT: GRAVITY_PARENT);
694 $mail['event-type'] = '';
695 $mail['attach'] = '';
703 * Creates an activity array for a given mail id
705 * @param integer $mail_id
706 * @param boolean $object_mode Is the activity item is used inside another object?
708 * @return array of activity
711 public static function createActivityFromMail($mail_id, $object_mode = false)
713 $mail = self::ItemArrayFromMail($mail_id);
714 $object = self::createNote($mail);
717 $data = ['@context' => ActivityPub::CONTEXT];
722 $data['id'] = $mail['uri'] . '#Create';
723 $data['type'] = 'Create';
724 $data['actor'] = $mail['author-link'];
725 $data['published'] = DateTimeFormat::utc($mail['created'] . '+00:00', DateTimeFormat::ATOM);
726 $data['instrument'] = self::getService();
727 $data = array_merge($data, self::createPermissionBlockForItem($mail, true));
729 if (empty($data['to']) && !empty($data['cc'])) {
730 $data['to'] = $data['cc'];
733 if (empty($data['to']) && !empty($data['bcc'])) {
734 $data['to'] = $data['bcc'];
740 $object['to'] = $data['to'];
741 $object['tag'] = [['type' => 'Mention', 'href' => $object['to'][0], 'name' => '']];
743 unset($object['cc']);
744 unset($object['bcc']);
746 $data['directMessage'] = true;
748 $data['object'] = $object;
750 $owner = User::getOwnerDataById($mail['uid']);
752 if (!$object_mode && !empty($owner)) {
753 return LDSignature::sign($data, $owner);
760 * Returns the activity type of a given item
764 * @return string with activity type
765 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
766 * @throws \ImagickException
768 private static function getTypeOfItem($item)
772 // Only check for a reshare, if it is a real reshare and no quoted reshare
773 if (strpos($item['body'], "[share") === 0) {
774 $announce = self::getAnnounceArray($item);
775 $reshared = !empty($announce);
780 } elseif ($item['verb'] == Activity::POST) {
781 if ($item['created'] == $item['edited']) {
786 } elseif ($item['verb'] == Activity::LIKE) {
788 } elseif ($item['verb'] == Activity::DISLIKE) {
790 } elseif ($item['verb'] == Activity::ATTEND) {
792 } elseif ($item['verb'] == Activity::ATTENDNO) {
794 } elseif ($item['verb'] == Activity::ATTENDMAYBE) {
795 $type = 'TentativeAccept';
796 } elseif ($item['verb'] == Activity::FOLLOW) {
798 } elseif ($item['verb'] == Activity::TAG) {
808 * Creates the activity or fetches it from the cache
810 * @param integer $item_id
811 * @param boolean $force Force new cache entry
813 * @return array with the activity
816 public static function createCachedActivityFromItem($item_id, $force = false)
818 $cachekey = 'APDelivery:createActivity:' . $item_id;
821 $data = DI::cache()->get($cachekey);
822 if (!is_null($data)) {
827 $data = ActivityPub\Transmitter::createActivityFromItem($item_id);
829 DI::cache()->set($cachekey, $data, Duration::QUARTER_HOUR);
834 * Creates an activity array for a given item id
836 * @param integer $item_id
837 * @param boolean $object_mode Is the activity item is used inside another object?
839 * @return array of activity
842 public static function createActivityFromItem($item_id, $object_mode = false)
844 $item = Item::selectFirst([], ['id' => $item_id, 'parent-network' => Protocol::NATIVE_SUPPORT]);
846 if (!DBA::isResult($item)) {
850 if ($item['wall'] && ($item['uri'] == $item['parent-uri'])) {
851 $owner = User::getOwnerDataById($item['uid']);
852 if (($owner['account-type'] == User::ACCOUNT_TYPE_COMMUNITY) && ($item['author-link'] != $owner['url'])) {
855 // Disguise forum posts as reshares. Will later be converted to a real announce
856 $item['body'] = share_header($item['author-name'], $item['author-link'], $item['author-avatar'],
857 $item['guid'], $item['created'], $item['plink']) . $item['body'] . '[/share]';
862 $condition = ['item-uri' => $item['uri'], 'protocol' => Conversation::PARCEL_ACTIVITYPUB];
863 $conversation = DBA::selectFirst('conversation', ['source'], $condition);
864 if (DBA::isResult($conversation)) {
865 $data = json_decode($conversation['source'], true);
871 $type = self::getTypeOfItem($item);
875 $data = ['@context' => ActivityPub::CONTEXT];
877 if ($item['deleted'] && ($item['gravity'] == GRAVITY_ACTIVITY)) {
879 } elseif ($item['deleted']) {
886 $data['id'] = $item['uri'] . '#' . $type;
887 $data['type'] = $type;
889 if (Item::isForumPost($item) && ($type != 'Announce')) {
890 $data['actor'] = $item['author-link'];
892 $data['actor'] = $item['owner-link'];
895 $data['published'] = DateTimeFormat::utc($item['created'] . '+00:00', DateTimeFormat::ATOM);
897 $data['instrument'] = self::getService();
899 $data = array_merge($data, self::createPermissionBlockForItem($item, false));
901 if (in_array($data['type'], ['Create', 'Update', 'Delete'])) {
902 $data['object'] = self::createNote($item);
903 } elseif ($data['type'] == 'Add') {
904 $data = self::createAddTag($item, $data);
905 } elseif ($data['type'] == 'Announce') {
906 $data = self::createAnnounce($item, $data);
907 } elseif ($data['type'] == 'Follow') {
908 $data['object'] = $item['parent-uri'];
909 } elseif ($data['type'] == 'Undo') {
910 $data['object'] = self::createActivityFromItem($item_id, true);
912 $data['diaspora:guid'] = $item['guid'];
913 if (!empty($item['signed_text'])) {
914 $data['diaspora:like'] = $item['signed_text'];
916 $data['object'] = $item['thr-parent'];
919 if (!empty($item['contact-uid'])) {
920 $uid = $item['contact-uid'];
925 $owner = User::getOwnerDataById($uid);
927 if (!$object_mode && !empty($owner)) {
928 return LDSignature::sign($data, $owner);
933 /// @todo Create "conversation" entry
937 * Creates a location entry for a given item array
941 * @return array with location array
943 private static function createLocation($item)
945 $location = ['type' => 'Place'];
947 if (!empty($item['location'])) {
948 $location['name'] = $item['location'];
953 if (empty($item['coord'])) {
954 $coord = Map::getCoordinates($item['location']);
956 $coords = explode(' ', $item['coord']);
957 if (count($coords) == 2) {
958 $coord = ['lat' => $coords[0], 'lon' => $coords[1]];
962 if (!empty($coord['lat']) && !empty($coord['lon'])) {
963 $location['latitude'] = $coord['lat'];
964 $location['longitude'] = $coord['lon'];
971 * Returns a tag array for a given item array
975 * @return array of tags
976 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
978 private static function createTagList($item)
982 $terms = Term::tagArrayFromItemId($item['id'], [Term::HASHTAG, Term::MENTION, Term::IMPLICIT_MENTION]);
983 foreach ($terms as $term) {
984 if ($term['type'] == Term::HASHTAG) {
985 $url = DI::baseUrl() . '/search?tag=' . urlencode($term['term']);
986 $tags[] = ['type' => 'Hashtag', 'href' => $url, 'name' => '#' . $term['term']];
987 } elseif ($term['type'] == Term::MENTION || $term['type'] == Term::IMPLICIT_MENTION) {
988 $contact = Contact::getDetailsByURL($term['url']);
989 if (!empty($contact['addr'])) {
990 $mention = '@' . $contact['addr'];
992 $mention = '@' . $term['url'];
995 $tags[] = ['type' => 'Mention', 'href' => $term['url'], 'name' => $mention];
999 $announce = self::getAnnounceArray($item);
1000 // Mention the original author upon commented reshares
1001 if (!empty($announce['comment'])) {
1002 $tags[] = ['type' => 'Mention', 'href' => $announce['actor']['url'], 'name' => '@' . $announce['actor']['addr']];
1009 * Adds attachment data to the JSON document
1011 * @param array $item Data of the item that is to be posted
1012 * @param string $type Object type
1014 * @return array with attachment data
1015 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1017 private static function createAttachmentList($item, $type)
1021 // Currently deactivated, since it creates side effects on Mastodon and Pleroma.
1022 // It will be reactivated, once this cleared.
1024 $attach_data = BBCode::getAttachmentData($item['body']);
1025 if (!empty($attach_data['url'])) {
1026 $attachment = ['type' => 'Page',
1027 'mediaType' => 'text/html',
1028 'url' => $attach_data['url']];
1030 if (!empty($attach_data['title'])) {
1031 $attachment['name'] = $attach_data['title'];
1034 if (!empty($attach_data['description'])) {
1035 $attachment['summary'] = $attach_data['description'];
1038 if (!empty($attach_data['image'])) {
1039 $imgdata = Images::getInfoFromURLCached($attach_data['image']);
1041 $attachment['icon'] = ['type' => 'Image',
1042 'mediaType' => $imgdata['mime'],
1043 'width' => $imgdata[0],
1044 'height' => $imgdata[1],
1045 'url' => $attach_data['image']];
1049 $attachments[] = $attachment;
1052 $arr = explode('[/attach],', $item['attach']);
1054 foreach ($arr as $r) {
1056 $cnt = preg_match('|\[attach\]href=\"(.*?)\" length=\"(.*?)\" type=\"(.*?)\" title=\"(.*?)\"|', $r, $matches);
1058 $attributes = ['type' => 'Document',
1059 'mediaType' => $matches[3],
1060 'url' => $matches[1],
1063 if (trim($matches[4]) != '') {
1064 $attributes['name'] = trim($matches[4]);
1067 $attachments[] = $attributes;
1072 if ($type != 'Note') {
1073 return $attachments;
1076 // Simplify image codes
1077 $body = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '[img]$3[/img]', $item['body']);
1079 // Grab all pictures without alternative descriptions and create attachments out of them
1080 if (preg_match_all("/\[img\]([^\[\]]*)\[\/img\]/Usi", $body, $pictures)) {
1081 foreach ($pictures[1] as $picture) {
1082 $imgdata = Images::getInfoFromURLCached($picture);
1084 $attachments[] = ['type' => 'Document',
1085 'mediaType' => $imgdata['mime'],
1092 // Grab all pictures with alternative description and create attachments out of them
1093 if (preg_match_all("/\[img=([^\[\]]*)\]([^\[\]]*)\[\/img\]/Usi", $body, $pictures, PREG_SET_ORDER)) {
1094 foreach ($pictures as $picture) {
1095 $imgdata = Images::getInfoFromURLCached($picture[1]);
1097 $attachments[] = ['type' => 'Document',
1098 'mediaType' => $imgdata['mime'],
1099 'url' => $picture[1],
1100 'name' => $picture[2]];
1105 return $attachments;
1109 * Callback function to replace a Friendica style mention in a mention that is used on AP
1111 * @param array $match Matching values for the callback
1112 * @return string Replaced mention
1113 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1115 private static function mentionCallback($match)
1117 if (empty($match[1])) {
1121 $data = Contact::getDetailsByURL($match[1]);
1122 if (empty($data['nick'])) {
1126 return '@[url=' . $data['url'] . ']' . $data['nick'] . '[/url]';
1130 * Remove image elements since they are added as attachment
1132 * @param string $body
1134 * @return string with removed images
1136 private static function removePictures($body)
1138 // Simplify image codes
1139 $body = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '[img]$3[/img]', $body);
1140 $body = preg_replace("/\[img\=(.*?)\](.*?)\[\/img\]/ism", '[img]$1[/img]', $body);
1142 // Now remove local links
1143 $body = preg_replace_callback(
1144 '/\[url=([^\[\]]*)\]\[img\](.*)\[\/img\]\[\/url\]/Usi',
1146 // We remove the link when it is a link to a local photo page
1147 if (Photo::isLocalPage($match[1])) {
1150 // otherwise we just return the link
1151 return '[url]' . $match[1] . '[/url]';
1156 // Remove all pictures
1157 $body = preg_replace("/\[img\]([^\[\]]*)\[\/img\]/Usi", '', $body);
1163 * Fetches the "context" value for a givem item array from the "conversation" table
1165 * @param array $item
1167 * @return string with context url
1168 * @throws \Exception
1170 private static function fetchContextURLForItem($item)
1172 $conversation = DBA::selectFirst('conversation', ['conversation-href', 'conversation-uri'], ['item-uri' => $item['parent-uri']]);
1173 if (DBA::isResult($conversation) && !empty($conversation['conversation-href'])) {
1174 $context_uri = $conversation['conversation-href'];
1175 } elseif (DBA::isResult($conversation) && !empty($conversation['conversation-uri'])) {
1176 $context_uri = $conversation['conversation-uri'];
1178 $context_uri = $item['parent-uri'] . '#context';
1180 return $context_uri;
1184 * Returns if the post contains sensitive content ("nsfw")
1186 * @param integer $item_id
1189 * @throws \Exception
1191 private static function isSensitive($item_id)
1193 $condition = ['otype' => TERM_OBJ_POST, 'oid' => $item_id, 'type' => TERM_HASHTAG, 'term' => 'nsfw'];
1194 return DBA::exists('term', $condition);
1198 * Creates event data
1200 * @param array $item
1202 * @return array with the event data
1203 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1205 public static function createEvent($item)
1208 $event['name'] = $item['event-summary'];
1209 $event['content'] = BBCode::convert($item['event-desc'], false, 9);
1210 $event['startTime'] = DateTimeFormat::utc($item['event-start'] . '+00:00', DateTimeFormat::ATOM);
1212 if (!$item['event-nofinish']) {
1213 $event['endTime'] = DateTimeFormat::utc($item['event-finish'] . '+00:00', DateTimeFormat::ATOM);
1216 if (!empty($item['event-location'])) {
1217 $item['location'] = $item['event-location'];
1218 $event['location'] = self::createLocation($item);
1225 * Creates a note/article object array
1227 * @param array $item
1229 * @return array with the object data
1230 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1231 * @throws \ImagickException
1233 public static function createNote($item)
1239 if ($item['event-type'] == 'event') {
1241 } elseif (!empty($item['title'])) {
1247 if ($item['deleted']) {
1248 $type = 'Tombstone';
1252 $data['id'] = $item['uri'];
1253 $data['type'] = $type;
1255 if ($item['deleted']) {
1259 $data['summary'] = BBCode::toPlaintext(BBCode::getAbstract($item['body'], Protocol::ACTIVITYPUB));
1261 if ($item['uri'] != $item['thr-parent']) {
1262 $data['inReplyTo'] = $item['thr-parent'];
1264 $data['inReplyTo'] = null;
1267 $data['diaspora:guid'] = $item['guid'];
1268 $data['published'] = DateTimeFormat::utc($item['created'] . '+00:00', DateTimeFormat::ATOM);
1270 if ($item['created'] != $item['edited']) {
1271 $data['updated'] = DateTimeFormat::utc($item['edited'] . '+00:00', DateTimeFormat::ATOM);
1274 $data['url'] = $item['plink'];
1275 $data['attributedTo'] = $item['author-link'];
1276 $data['sensitive'] = self::isSensitive($item['id']);
1277 $data['context'] = self::fetchContextURLForItem($item);
1279 if (!empty($item['title'])) {
1280 $data['name'] = BBCode::toPlaintext($item['title'], false);
1283 $permission_block = self::createPermissionBlockForItem($item, false);
1285 $body = $item['body'];
1287 if (empty($item['uid']) || !Feature::isEnabled($item['uid'], 'explicit_mentions')) {
1288 $body = self::prependMentions($body, $permission_block);
1291 if ($type == 'Note') {
1292 $body = self::removePictures($body);
1293 } elseif (($type == 'Article') && empty($data['summary'])) {
1294 $data['summary'] = BBCode::toPlaintext(Plaintext::shorten(self::removePictures($body), 1000));
1297 if ($type == 'Event') {
1298 $data = array_merge($data, self::createEvent($item));
1300 $regexp = "/[@!]\[url\=([^\[\]]*)\].*?\[\/url\]/ism";
1301 $body = preg_replace_callback($regexp, ['self', 'mentionCallback'], $body);
1303 $data['content'] = BBCode::convert($body, false, 9);
1306 // The regular "content" field does contain a minimized HTML. This is done since systems like
1307 // Mastodon has got problems with - for example - embedded pictures.
1308 // The contentMap does contain the unmodified HTML.
1309 $language = self::getLanguage($item);
1310 if (!empty($language)) {
1311 $regexp = "/[@!]\[url\=([^\[\]]*)\].*?\[\/url\]/ism";
1312 $richbody = preg_replace_callback($regexp, ['self', 'mentionCallback'], $item['body']);
1313 $richbody = BBCode::removeAttachment($richbody);
1315 $data['contentMap'][$language] = BBCode::convert($richbody, false);
1318 $data['source'] = ['content' => $item['body'], 'mediaType' => "text/bbcode"];
1320 if (!empty($item['signed_text']) && ($item['uri'] != $item['thr-parent'])) {
1321 $data['diaspora:comment'] = $item['signed_text'];
1324 $data['attachment'] = self::createAttachmentList($item, $type);
1325 $data['tag'] = self::createTagList($item);
1327 if (empty($data['location']) && (!empty($item['coord']) || !empty($item['location']))) {
1328 $data['location'] = self::createLocation($item);
1331 if (!empty($item['app'])) {
1332 $data['generator'] = ['type' => 'Application', 'name' => $item['app']];
1335 $data = array_merge($data, $permission_block);
1341 * Fetches the language from the post, the user or the system.
1343 * @param array $item
1345 * @return string language string
1347 private static function getLanguage(array $item)
1349 // Try to fetch the language from the post itself
1350 if (!empty($item['language'])) {
1351 $languages = array_keys(json_decode($item['language'], true));
1352 if (!empty($languages[0])) {
1353 return $languages[0];
1357 // Otherwise use the user's language
1358 if (!empty($item['uid'])) {
1359 $user = DBA::selectFirst('user', ['language'], ['uid' => $item['uid']]);
1360 if (!empty($user['language'])) {
1361 return $user['language'];
1365 // And finally just use the system language
1366 return DI::config()->get('system', 'language');
1370 * Creates an an "add tag" entry
1372 * @param array $item
1373 * @param array $data activity data
1375 * @return array with activity data for adding tags
1376 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1377 * @throws \ImagickException
1379 private static function createAddTag($item, $data)
1381 $object = XML::parseString($item['object'], false);
1382 $target = XML::parseString($item["target"], false);
1384 $data['diaspora:guid'] = $item['guid'];
1385 $data['actor'] = $item['author-link'];
1386 $data['target'] = (string)$target->id;
1387 $data['summary'] = BBCode::toPlaintext($item['body']);
1388 $data['object'] = ['id' => (string)$object->id, 'type' => 'tag', 'name' => (string)$object->title, 'content' => (string)$object->content];
1394 * Creates an announce object entry
1396 * @param array $item
1397 * @param array $data activity data
1399 * @return array with activity data
1400 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1401 * @throws \ImagickException
1403 private static function createAnnounce($item, $data)
1405 $orig_body = $item['body'];
1406 $announce = self::getAnnounceArray($item);
1407 if (empty($announce)) {
1408 $data['type'] = 'Create';
1409 $data['object'] = self::createNote($item);
1413 if (empty($announce['comment'])) {
1414 // Pure announce, without a quote
1415 $data['type'] = 'Announce';
1416 $data['object'] = $announce['object']['uri'];
1421 $data['type'] = 'Create';
1422 $item['body'] = $announce['comment'] . "\n" . $announce['object']['plink'];
1423 $data['object'] = self::createNote($item);
1425 /// @todo Finally descide how to implement this in AP. This is a possible way:
1426 $data['object']['attachment'][] = self::createNote($announce['object']);
1428 $data['object']['source']['content'] = $orig_body;
1433 * Return announce related data if the item is an annunce
1435 * @param array $item
1439 public static function getAnnounceArray($item)
1441 $reshared = Item::getShareArray($item);
1442 if (empty($reshared['guid'])) {
1446 $reshared_item = Item::selectFirst([], ['guid' => $reshared['guid']]);
1447 if (!DBA::isResult($reshared_item)) {
1451 if (!in_array($reshared_item['network'], [Protocol::ACTIVITYPUB, Protocol::DFRN])) {
1455 $profile = APContact::getByURL($reshared_item['author-link'], false);
1456 if (empty($profile)) {
1460 return ['object' => $reshared_item, 'actor' => $profile, 'comment' => $reshared['comment']];
1464 * Checks if the provided item array is an announce
1466 * @param array $item
1470 public static function isAnnounce($item)
1472 $announce = self::getAnnounceArray($item);
1473 if (empty($announce)) {
1477 return empty($announce['comment']);
1481 * Creates an activity id for a given contact id
1483 * @param integer $cid Contact ID of target
1485 * @return bool|string activity id
1487 public static function activityIDFromContact($cid)
1489 $contact = DBA::selectFirst('contact', ['uid', 'id', 'created'], ['id' => $cid]);
1490 if (!DBA::isResult($contact)) {
1494 $hash = hash('ripemd128', $contact['uid'].'-'.$contact['id'].'-'.$contact['created']);
1495 $uuid = substr($hash, 0, 8). '-' . substr($hash, 8, 4) . '-' . substr($hash, 12, 4) . '-' . substr($hash, 16, 4) . '-' . substr($hash, 20, 12);
1496 return DI::baseUrl() . '/activity/' . $uuid;
1500 * Transmits a contact suggestion to a given inbox
1502 * @param integer $uid User ID
1503 * @param string $inbox Target inbox
1504 * @param integer $suggestion_id Suggestion ID
1506 * @return boolean was the transmission successful?
1507 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1509 public static function sendContactSuggestion($uid, $inbox, $suggestion_id)
1511 $owner = User::getOwnerDataById($uid);
1513 $suggestion = DBA::selectFirst('fsuggest', ['url', 'note', 'created'], ['id' => $suggestion_id]);
1515 $data = ['@context' => ActivityPub::CONTEXT,
1516 'id' => DI::baseUrl() . '/activity/' . System::createGUID(),
1517 'type' => 'Announce',
1518 'actor' => $owner['url'],
1519 'object' => $suggestion['url'],
1520 'content' => $suggestion['note'],
1521 'instrument' => self::getService(),
1522 'to' => [ActivityPub::PUBLIC_COLLECTION],
1525 $signed = LDSignature::sign($data, $owner);
1527 Logger::log('Deliver profile deletion for user ' . $uid . ' to ' . $inbox . ' via ActivityPub', Logger::DEBUG);
1528 return HTTPSignature::transmit($signed, $inbox, $uid);
1532 * Transmits a profile relocation to a given inbox
1534 * @param integer $uid User ID
1535 * @param string $inbox Target inbox
1537 * @return boolean was the transmission successful?
1538 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1540 public static function sendProfileRelocation($uid, $inbox)
1542 $owner = User::getOwnerDataById($uid);
1544 $data = ['@context' => ActivityPub::CONTEXT,
1545 'id' => DI::baseUrl() . '/activity/' . System::createGUID(),
1546 'type' => 'dfrn:relocate',
1547 'actor' => $owner['url'],
1548 'object' => $owner['url'],
1549 'published' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
1550 'instrument' => self::getService(),
1551 'to' => [ActivityPub::PUBLIC_COLLECTION],
1554 $signed = LDSignature::sign($data, $owner);
1556 Logger::log('Deliver profile relocation for user ' . $uid . ' to ' . $inbox . ' via ActivityPub', Logger::DEBUG);
1557 return HTTPSignature::transmit($signed, $inbox, $uid);
1561 * Transmits a profile deletion to a given inbox
1563 * @param integer $uid User ID
1564 * @param string $inbox Target inbox
1566 * @return boolean was the transmission successful?
1567 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1569 public static function sendProfileDeletion($uid, $inbox)
1571 $owner = User::getOwnerDataById($uid);
1573 if (empty($owner)) {
1574 Logger::error('No owner data found, the deletion message cannot be processed.', ['user' => $uid]);
1578 if (empty($owner['uprvkey'])) {
1579 Logger::error('No private key for owner found, the deletion message cannot be processed.', ['user' => $uid]);
1583 $data = ['@context' => ActivityPub::CONTEXT,
1584 'id' => DI::baseUrl() . '/activity/' . System::createGUID(),
1586 'actor' => $owner['url'],
1587 'object' => $owner['url'],
1588 'published' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
1589 'instrument' => self::getService(),
1590 'to' => [ActivityPub::PUBLIC_COLLECTION],
1593 $signed = LDSignature::sign($data, $owner);
1595 Logger::log('Deliver profile deletion for user ' . $uid . ' to ' . $inbox . ' via ActivityPub', Logger::DEBUG);
1596 return HTTPSignature::transmit($signed, $inbox, $uid);
1600 * Transmits a profile change to a given inbox
1602 * @param integer $uid User ID
1603 * @param string $inbox Target inbox
1605 * @return boolean was the transmission successful?
1606 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1607 * @throws \ImagickException
1609 public static function sendProfileUpdate($uid, $inbox)
1611 $owner = User::getOwnerDataById($uid);
1612 $profile = APContact::getByURL($owner['url']);
1614 $data = ['@context' => ActivityPub::CONTEXT,
1615 'id' => DI::baseUrl() . '/activity/' . System::createGUID(),
1617 'actor' => $owner['url'],
1618 'object' => self::getProfile($uid),
1619 'published' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
1620 'instrument' => self::getService(),
1621 'to' => [$profile['followers']],
1624 $signed = LDSignature::sign($data, $owner);
1626 Logger::log('Deliver profile update for user ' . $uid . ' to ' . $inbox . ' via ActivityPub', Logger::DEBUG);
1627 return HTTPSignature::transmit($signed, $inbox, $uid);
1631 * Transmits a given activity to a target
1633 * @param string $activity Type name
1634 * @param string $target Target profile
1635 * @param integer $uid User ID
1637 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1638 * @throws \ImagickException
1639 * @throws \Exception
1641 public static function sendActivity($activity, $target, $uid, $id = '')
1643 $profile = APContact::getByURL($target);
1644 if (empty($profile['inbox'])) {
1645 Logger::warning('No inbox found for target', ['target' => $target, 'profile' => $profile]);
1649 $owner = User::getOwnerDataById($uid);
1652 $id = DI::baseUrl() . '/activity/' . System::createGUID();
1655 $data = ['@context' => ActivityPub::CONTEXT,
1657 'type' => $activity,
1658 'actor' => $owner['url'],
1659 'object' => $profile['url'],
1660 'instrument' => self::getService(),
1661 'to' => [$profile['url']]];
1663 Logger::log('Sending activity ' . $activity . ' to ' . $target . ' for user ' . $uid, Logger::DEBUG);
1665 $signed = LDSignature::sign($data, $owner);
1666 return HTTPSignature::transmit($signed, $profile['inbox'], $uid);
1670 * Transmits a "follow object" activity to a target
1671 * This is a preparation for sending automated "follow" requests when receiving "Announce" messages
1673 * @param string $object Object URL
1674 * @param string $target Target profile
1675 * @param integer $uid User ID
1677 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1678 * @throws \ImagickException
1679 * @throws \Exception
1681 public static function sendFollowObject($object, $target, $uid = 0)
1683 $profile = APContact::getByURL($target);
1684 if (empty($profile['inbox'])) {
1685 Logger::warning('No inbox found for target', ['target' => $target, 'profile' => $profile]);
1690 // Fetch the list of administrators
1691 $admin_mail = explode(',', str_replace(' ', '', DI::config()->get('config', 'admin_email')));
1693 // We need to use some user as a sender. It doesn't care who it will send. We will use an administrator account.
1694 $condition = ['verified' => true, 'blocked' => false, 'account_removed' => false, 'account_expired' => false, 'email' => $admin_mail];
1695 $first_user = DBA::selectFirst('user', ['uid'], $condition);
1696 $uid = $first_user['uid'];
1699 $condition = ['verb' => Activity::FOLLOW, 'uid' => 0, 'parent-uri' => $object,
1700 'author-id' => Contact::getPublicIdByUserId($uid)];
1701 if (Item::exists($condition)) {
1702 Logger::log('Follow for ' . $object . ' for user ' . $uid . ' does already exist.', Logger::DEBUG);
1706 $owner = User::getOwnerDataById($uid);
1708 $data = ['@context' => ActivityPub::CONTEXT,
1709 'id' => DI::baseUrl() . '/activity/' . System::createGUID(),
1711 'actor' => $owner['url'],
1712 'object' => $object,
1713 'instrument' => self::getService(),
1714 'to' => [$profile['url']]];
1716 Logger::log('Sending follow ' . $object . ' to ' . $target . ' for user ' . $uid, Logger::DEBUG);
1718 $signed = LDSignature::sign($data, $owner);
1719 return HTTPSignature::transmit($signed, $profile['inbox'], $uid);
1723 * Transmit a message that the contact request had been accepted
1725 * @param string $target Target profile
1727 * @param integer $uid User ID
1728 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1729 * @throws \ImagickException
1731 public static function sendContactAccept($target, $id, $uid)
1733 $profile = APContact::getByURL($target);
1734 if (empty($profile['inbox'])) {
1735 Logger::warning('No inbox found for target', ['target' => $target, 'profile' => $profile]);
1739 $owner = User::getOwnerDataById($uid);
1740 $data = ['@context' => ActivityPub::CONTEXT,
1741 'id' => DI::baseUrl() . '/activity/' . System::createGUID(),
1743 'actor' => $owner['url'],
1745 'id' => (string)$id,
1747 'actor' => $profile['url'],
1748 'object' => $owner['url']
1750 'instrument' => self::getService(),
1751 'to' => [$profile['url']]];
1753 Logger::debug('Sending accept to ' . $target . ' for user ' . $uid . ' with id ' . $id);
1755 $signed = LDSignature::sign($data, $owner);
1756 HTTPSignature::transmit($signed, $profile['inbox'], $uid);
1760 * Reject a contact request or terminates the contact relation
1762 * @param string $target Target profile
1764 * @param integer $uid User ID
1765 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1766 * @throws \ImagickException
1768 public static function sendContactReject($target, $id, $uid)
1770 $profile = APContact::getByURL($target);
1771 if (empty($profile['inbox'])) {
1772 Logger::warning('No inbox found for target', ['target' => $target, 'profile' => $profile]);
1776 $owner = User::getOwnerDataById($uid);
1777 $data = ['@context' => ActivityPub::CONTEXT,
1778 'id' => DI::baseUrl() . '/activity/' . System::createGUID(),
1780 'actor' => $owner['url'],
1782 'id' => (string)$id,
1784 'actor' => $profile['url'],
1785 'object' => $owner['url']
1787 'instrument' => self::getService(),
1788 'to' => [$profile['url']]];
1790 Logger::debug('Sending reject to ' . $target . ' for user ' . $uid . ' with id ' . $id);
1792 $signed = LDSignature::sign($data, $owner);
1793 HTTPSignature::transmit($signed, $profile['inbox'], $uid);
1797 * Transmits a message that we don't want to follow this contact anymore
1799 * @param string $target Target profile
1800 * @param integer $uid User ID
1801 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1802 * @throws \ImagickException
1803 * @throws \Exception
1805 public static function sendContactUndo($target, $cid, $uid)
1807 $profile = APContact::getByURL($target);
1808 if (empty($profile['inbox'])) {
1809 Logger::warning('No inbox found for target', ['target' => $target, 'profile' => $profile]);
1813 $object_id = self::activityIDFromContact($cid);
1814 if (empty($object_id)) {
1818 $id = DI::baseUrl() . '/activity/' . System::createGUID();
1820 $owner = User::getOwnerDataById($uid);
1821 $data = ['@context' => ActivityPub::CONTEXT,
1824 'actor' => $owner['url'],
1825 'object' => ['id' => $object_id, 'type' => 'Follow',
1826 'actor' => $owner['url'],
1827 'object' => $profile['url']],
1828 'instrument' => self::getService(),
1829 'to' => [$profile['url']]];
1831 Logger::log('Sending undo to ' . $target . ' for user ' . $uid . ' with id ' . $id, Logger::DEBUG);
1833 $signed = LDSignature::sign($data, $owner);
1834 HTTPSignature::transmit($signed, $profile['inbox'], $uid);
1837 private static function prependMentions($body, array $permission_block)
1839 if (DI::config()->get('system', 'disable_implicit_mentions')) {
1845 foreach ($permission_block['to'] as $profile_url) {
1846 $profile = Contact::getDetailsByURL($profile_url);
1847 if (!empty($profile['addr'])
1848 && $profile['contact-type'] != Contact::TYPE_COMMUNITY
1849 && !strstr($body, $profile['addr'])
1850 && !strstr($body, $profile_url)
1852 $mentions[] = '@[url=' . $profile_url . ']' . $profile['nick'] . '[/url]';
1856 $mentions[] = $body;
1858 return implode(' ', $mentions);