3 * @file src/Protocol/ActivityPub/Transmitter.php
5 namespace Friendica\Protocol\ActivityPub;
7 use Friendica\BaseObject;
8 use Friendica\Content\Feature;
9 use Friendica\Content\Text\BBCode;
10 use Friendica\Content\Text\Plaintext;
11 use Friendica\Core\Cache;
12 use Friendica\Core\Config;
13 use Friendica\Core\Logger;
14 use Friendica\Core\Protocol;
15 use Friendica\Core\System;
16 use Friendica\Database\DBA;
18 use Friendica\Model\APContact;
19 use Friendica\Model\Contact;
20 use Friendica\Model\Conversation;
21 use Friendica\Model\Item;
22 use Friendica\Model\Profile;
23 use Friendica\Model\Photo;
24 use Friendica\Model\Term;
25 use Friendica\Model\User;
26 use Friendica\Protocol\Activity;
27 use Friendica\Protocol\ActivityPub;
28 use Friendica\Util\DateTimeFormat;
29 use Friendica\Util\HTTPSignature;
30 use Friendica\Util\Images;
31 use Friendica\Util\JsonLD;
32 use Friendica\Util\LDSignature;
33 use Friendica\Util\Map;
34 use Friendica\Util\Network;
35 use Friendica\Util\XML;
37 require_once 'include/api.php';
38 require_once 'mod/share.php';
41 * @brief ActivityPub Transmitter Protocol class
49 * collects the lost of followers of the given owner
51 * @param array $owner Owner array
52 * @param integer $page Page number
54 * @return array of owners
55 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
57 public static function getFollowers($owner, $page = null)
59 $condition = ['rel' => [Contact::FOLLOWER, Contact::FRIEND], 'network' => Protocol::NATIVE_SUPPORT, 'uid' => $owner['uid'],
60 'self' => false, 'deleted' => false, 'hidden' => false, 'archive' => false, 'pending' => false];
61 $count = DBA::count('contact', $condition);
63 $data = ['@context' => ActivityPub::CONTEXT];
64 $data['id'] = System::baseUrl() . '/followers/' . $owner['nickname'];
65 $data['type'] = 'OrderedCollection';
66 $data['totalItems'] = $count;
68 // When we hide our friends we will only show the pure number but don't allow more.
69 $profile = Profile::getByUID($owner['uid']);
70 if (!empty($profile['hide-friends'])) {
75 $data['first'] = System::baseUrl() . '/followers/' . $owner['nickname'] . '?page=1';
77 $data['type'] = 'OrderedCollectionPage';
80 $contacts = DBA::select('contact', ['url'], $condition, ['limit' => [($page - 1) * 100, 100]]);
81 while ($contact = DBA::fetch($contacts)) {
82 $list[] = $contact['url'];
86 $data['next'] = System::baseUrl() . '/followers/' . $owner['nickname'] . '?page=' . ($page + 1);
89 $data['partOf'] = System::baseUrl() . '/followers/' . $owner['nickname'];
91 $data['orderedItems'] = $list;
98 * Create list of following contacts
100 * @param array $owner Owner array
101 * @param integer $page Page numbe
103 * @return array of following contacts
104 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
106 public static function getFollowing($owner, $page = null)
108 $condition = ['rel' => [Contact::SHARING, Contact::FRIEND], 'network' => Protocol::NATIVE_SUPPORT, 'uid' => $owner['uid'],
109 'self' => false, 'deleted' => false, 'hidden' => false, 'archive' => false, 'pending' => false];
110 $count = DBA::count('contact', $condition);
112 $data = ['@context' => ActivityPub::CONTEXT];
113 $data['id'] = System::baseUrl() . '/following/' . $owner['nickname'];
114 $data['type'] = 'OrderedCollection';
115 $data['totalItems'] = $count;
117 // When we hide our friends we will only show the pure number but don't allow more.
118 $profile = Profile::getByUID($owner['uid']);
119 if (!empty($profile['hide-friends'])) {
124 $data['first'] = System::baseUrl() . '/following/' . $owner['nickname'] . '?page=1';
126 $data['type'] = 'OrderedCollectionPage';
129 $contacts = DBA::select('contact', ['url'], $condition, ['limit' => [($page - 1) * 100, 100]]);
130 while ($contact = DBA::fetch($contacts)) {
131 $list[] = $contact['url'];
135 $data['next'] = System::baseUrl() . '/following/' . $owner['nickname'] . '?page=' . ($page + 1);
138 $data['partOf'] = System::baseUrl() . '/following/' . $owner['nickname'];
140 $data['orderedItems'] = $list;
147 * Public posts for the given owner
149 * @param array $owner Owner array
150 * @param integer $page Page numbe
152 * @return array of posts
153 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
154 * @throws \ImagickException
156 public static function getOutbox($owner, $page = null)
158 $public_contact = Contact::getIdForURL($owner['url'], 0, true);
160 $condition = ['uid' => 0, 'contact-id' => $public_contact, 'author-id' => $public_contact,
161 'private' => false, 'gravity' => [GRAVITY_PARENT, GRAVITY_COMMENT],
162 'deleted' => false, 'visible' => true, 'moderated' => false];
163 $count = DBA::count('item', $condition);
165 $data = ['@context' => ActivityPub::CONTEXT];
166 $data['id'] = System::baseUrl() . '/outbox/' . $owner['nickname'];
167 $data['type'] = 'OrderedCollection';
168 $data['totalItems'] = $count;
171 $data['first'] = System::baseUrl() . '/outbox/' . $owner['nickname'] . '?page=1';
173 $data['type'] = 'OrderedCollectionPage';
176 $condition['parent-network'] = Protocol::NATIVE_SUPPORT;
178 $items = Item::select(['id'], $condition, ['limit' => [($page - 1) * 20, 20], 'order' => ['created' => true]]);
179 while ($item = Item::fetch($items)) {
180 $activity = self::createActivityFromItem($item['id'], true);
181 // Only list "Create" activity objects here, no reshares
182 if (is_array($activity['object']) && ($activity['type'] == 'Create')) {
183 $list[] = $activity['object'];
188 $data['next'] = System::baseUrl() . '/outbox/' . $owner['nickname'] . '?page=' . ($page + 1);
191 $data['partOf'] = System::baseUrl() . '/outbox/' . $owner['nickname'];
193 $data['orderedItems'] = $list;
200 * Return the service array containing information the used software and it's url
202 * @return array with service data
204 private static function getService()
206 return ['type' => 'Service',
207 'name' => FRIENDICA_PLATFORM . " '" . FRIENDICA_CODENAME . "' " . FRIENDICA_VERSION . '-' . DB_UPDATE_VERSION,
208 'url' => DI::app()->getBaseURL()];
212 * Return the ActivityPub profile of the given user
214 * @param integer $uid User ID
215 * @return array with profile data
216 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
218 public static function getProfile($uid)
220 $condition = ['uid' => $uid, 'blocked' => false, 'account_expired' => false,
221 'account_removed' => false, 'verified' => true];
222 $fields = ['guid', 'nickname', 'pubkey', 'account-type', 'page-flags'];
223 $user = DBA::selectFirst('user', $fields, $condition);
224 if (!DBA::isResult($user)) {
228 $fields = ['locality', 'region', 'country-name'];
229 $profile = DBA::selectFirst('profile', $fields, ['uid' => $uid, 'is-default' => true]);
230 if (!DBA::isResult($profile)) {
234 $fields = ['name', 'url', 'location', 'about', 'avatar', 'photo'];
235 $contact = DBA::selectFirst('contact', $fields, ['uid' => $uid, 'self' => true]);
236 if (!DBA::isResult($contact)) {
240 $data = ['@context' => ActivityPub::CONTEXT];
241 $data['id'] = $contact['url'];
242 $data['diaspora:guid'] = $user['guid'];
243 $data['type'] = ActivityPub::ACCOUNT_TYPES[$user['account-type']];
244 $data['following'] = System::baseUrl() . '/following/' . $user['nickname'];
245 $data['followers'] = System::baseUrl() . '/followers/' . $user['nickname'];
246 $data['inbox'] = System::baseUrl() . '/inbox/' . $user['nickname'];
247 $data['outbox'] = System::baseUrl() . '/outbox/' . $user['nickname'];
248 $data['preferredUsername'] = $user['nickname'];
249 $data['name'] = $contact['name'];
250 $data['vcard:hasAddress'] = ['@type' => 'vcard:Home', 'vcard:country-name' => $profile['country-name'],
251 'vcard:region' => $profile['region'], 'vcard:locality' => $profile['locality']];
252 $data['summary'] = $contact['about'];
253 $data['url'] = $contact['url'];
254 $data['manuallyApprovesFollowers'] = in_array($user['page-flags'], [User::PAGE_FLAGS_NORMAL, User::PAGE_FLAGS_PRVGROUP]);
255 $data['publicKey'] = ['id' => $contact['url'] . '#main-key',
256 'owner' => $contact['url'],
257 'publicKeyPem' => $user['pubkey']];
258 $data['endpoints'] = ['sharedInbox' => System::baseUrl() . '/inbox'];
259 $data['icon'] = ['type' => 'Image',
260 'url' => $contact['photo']];
262 $data['generator'] = self::getService();
264 // tags: https://kitty.town/@inmysocks/100656097926961126.json
269 * @param string $username
271 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
273 public static function getDeletedUser($username)
276 '@context' => ActivityPub::CONTEXT,
277 'id' => System::baseUrl() . '/profile/' . $username,
278 'type' => 'Tombstone',
279 'published' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
280 'updated' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
281 'deleted' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
286 * Returns an array with permissions of a given item array
290 * @return array with permissions
291 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
292 * @throws \ImagickException
294 private static function fetchPermissionBlockFromConversation($item)
296 if (empty($item['thr-parent'])) {
300 $condition = ['item-uri' => $item['thr-parent'], 'protocol' => Conversation::PARCEL_ACTIVITYPUB];
301 $conversation = DBA::selectFirst('conversation', ['source'], $condition);
302 if (!DBA::isResult($conversation)) {
306 $activity = json_decode($conversation['source'], true);
308 $actor = JsonLD::fetchElement($activity, 'actor', 'id');
309 $profile = APContact::getByURL($actor);
311 $item_profile = APContact::getByURL($item['author-link']);
312 $exclude[] = $item['author-link'];
314 if ($item['gravity'] == GRAVITY_PARENT) {
315 $exclude[] = $item['owner-link'];
318 $permissions['to'][] = $actor;
320 foreach (['to', 'cc', 'bto', 'bcc'] as $element) {
321 if (empty($activity[$element])) {
324 if (is_string($activity[$element])) {
325 $activity[$element] = [$activity[$element]];
328 foreach ($activity[$element] as $receiver) {
329 if ($receiver == $profile['followers'] && !empty($item_profile['followers'])) {
330 $permissions[$element][] = $item_profile['followers'];
331 } elseif (!in_array($receiver, $exclude)) {
332 $permissions[$element][] = $receiver;
340 * Creates an array of permissions from an item thread
342 * @param array $item Item array
343 * @param boolean $blindcopy addressing via "bcc" or "cc"?
344 * @param integer $last_id Last item id for adding receivers
345 * @param boolean $forum_mode "true" means that we are sending content to a forum
347 * @return array with permission data
348 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
349 * @throws \ImagickException
351 private static function createPermissionBlockForItem($item, $blindcopy, $last_id = 0, $forum_mode = false)
354 $last_id = $item['id'];
359 // Check if we should always deliver our stuff via BCC
360 if (!empty($item['uid'])) {
361 $profile = Profile::getByUID($item['uid']);
362 if (!empty($profile)) {
363 $always_bcc = $profile['hide-friends'];
367 if (Config::get('system', 'ap_always_bcc')) {
371 if (self::isAnnounce($item) || Config::get('debug', 'total_ap_delivery')) {
372 // Will be activated in a later step
373 $networks = Protocol::FEDERATED;
375 // For now only send to these contacts:
376 $networks = [Protocol::ACTIVITYPUB, Protocol::OSTATUS];
379 $data = ['to' => [], 'cc' => [], 'bcc' => []];
381 if ($item['gravity'] == GRAVITY_PARENT) {
382 $actor_profile = APContact::getByURL($item['owner-link']);
384 $actor_profile = APContact::getByURL($item['author-link']);
387 $terms = Term::tagArrayFromItemId($item['id'], [Term::MENTION, Term::IMPLICIT_MENTION]);
389 if (!$item['private']) {
390 // Directly mention the original author upon a quoted reshare.
391 // Else just ensure that the original author receives the reshare.
392 $announce = self::getAnnounceArray($item);
393 if (!empty($announce['comment'])) {
394 $data['to'][] = $announce['actor']['url'];
395 } elseif (!empty($announce)) {
396 $data['cc'][] = $announce['actor']['url'];
399 $data = array_merge($data, self::fetchPermissionBlockFromConversation($item));
401 $data['to'][] = ActivityPub::PUBLIC_COLLECTION;
403 foreach ($terms as $term) {
404 $profile = APContact::getByURL($term['url'], false);
405 if (!empty($profile)) {
406 $data['to'][] = $profile['url'];
410 $receiver_list = Item::enumeratePermissions($item, true);
412 foreach ($terms as $term) {
413 $cid = Contact::getIdForURL($term['url'], $item['uid']);
414 if (!empty($cid) && in_array($cid, $receiver_list)) {
415 $contact = DBA::selectFirst('contact', ['url', 'network', 'protocol'], ['id' => $cid]);
416 if (!DBA::isResult($contact) || (!in_array($contact['network'], $networks) && ($contact['protocol'] != Protocol::ACTIVITYPUB))) {
420 if (!empty($profile = APContact::getByURL($contact['url'], false))) {
421 $data['to'][] = $profile['url'];
426 foreach ($receiver_list as $receiver) {
427 $contact = DBA::selectFirst('contact', ['url', 'hidden', 'network', 'protocol'], ['id' => $receiver]);
428 if (!DBA::isResult($contact) || (!in_array($contact['network'], $networks) && ($contact['protocol'] != Protocol::ACTIVITYPUB))) {
432 if (!empty($profile = APContact::getByURL($contact['url'], false))) {
433 if ($contact['hidden'] || $always_bcc) {
434 $data['bcc'][] = $profile['url'];
436 $data['cc'][] = $profile['url'];
442 if (!empty($item['parent'])) {
443 $parents = Item::select(['id', 'author-link', 'owner-link', 'gravity', 'uri'], ['parent' => $item['parent']]);
444 while ($parent = Item::fetch($parents)) {
445 if ($parent['gravity'] == GRAVITY_PARENT) {
446 $profile = APContact::getByURL($parent['owner-link'], false);
447 if (!empty($profile)) {
448 if ($item['gravity'] != GRAVITY_PARENT) {
449 // Comments to forums are directed to the forum
450 // But comments to forums aren't directed to the followers collection
451 if ($profile['type'] == 'Group') {
452 $data['to'][] = $profile['url'];
454 $data['cc'][] = $profile['url'];
455 if (!$item['private'] && !empty($actor_profile['followers'])) {
456 $data['cc'][] = $actor_profile['followers'];
460 // Public thread parent post always are directed to the followers
461 if (!$item['private'] && !$forum_mode) {
462 $data['cc'][] = $actor_profile['followers'];
468 // Don't include data from future posts
469 if ($parent['id'] >= $last_id) {
473 $profile = APContact::getByURL($parent['author-link'], false);
474 if (!empty($profile)) {
475 if (($profile['type'] == 'Group') || ($parent['uri'] == $item['thr-parent'])) {
476 $data['to'][] = $profile['url'];
478 $data['cc'][] = $profile['url'];
482 DBA::close($parents);
485 $data['to'] = array_unique($data['to']);
486 $data['cc'] = array_unique($data['cc']);
487 $data['bcc'] = array_unique($data['bcc']);
489 if (($key = array_search($item['author-link'], $data['to'])) !== false) {
490 unset($data['to'][$key]);
493 if (($key = array_search($item['author-link'], $data['cc'])) !== false) {
494 unset($data['cc'][$key]);
497 if (($key = array_search($item['author-link'], $data['bcc'])) !== false) {
498 unset($data['bcc'][$key]);
501 foreach ($data['to'] as $to) {
502 if (($key = array_search($to, $data['cc'])) !== false) {
503 unset($data['cc'][$key]);
506 if (($key = array_search($to, $data['bcc'])) !== false) {
507 unset($data['bcc'][$key]);
511 foreach ($data['cc'] as $cc) {
512 if (($key = array_search($cc, $data['bcc'])) !== false) {
513 unset($data['bcc'][$key]);
517 $receivers = ['to' => array_values($data['to']), 'cc' => array_values($data['cc']), 'bcc' => array_values($data['bcc'])];
520 unset($receivers['bcc']);
527 * Check if an inbox is archived
529 * @param string $url Inbox url
531 * @return boolean "true" if inbox is archived
533 private static function archivedInbox($url)
535 return DBA::exists('inbox-status', ['url' => $url, 'archive' => true]);
539 * Fetches a list of inboxes of followers of a given user
541 * @param integer $uid User ID
542 * @param boolean $personal fetch personal inboxes
544 * @return array of follower inboxes
545 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
546 * @throws \ImagickException
548 public static function fetchTargetInboxesforUser($uid, $personal = false)
552 if (Config::get('debug', 'total_ap_delivery')) {
553 // Will be activated in a later step
554 $networks = Protocol::FEDERATED;
556 // For now only send to these contacts:
557 $networks = [Protocol::ACTIVITYPUB, Protocol::OSTATUS];
560 $condition = ['uid' => $uid, 'archive' => false, 'pending' => false];
563 $condition['rel'] = [Contact::FOLLOWER, Contact::FRIEND];
566 $contacts = DBA::select('contact', ['url', 'network', 'protocol'], $condition);
567 while ($contact = DBA::fetch($contacts)) {
568 if (Contact::isLocal($contact['url'])) {
572 if (!in_array($contact['network'], $networks) && ($contact['protocol'] != Protocol::ACTIVITYPUB)) {
576 if (Network::isUrlBlocked($contact['url'])) {
580 $profile = APContact::getByURL($contact['url'], false);
581 if (!empty($profile)) {
582 if (empty($profile['sharedinbox']) || $personal) {
583 $target = $profile['inbox'];
585 $target = $profile['sharedinbox'];
587 if (!self::archivedInbox($target)) {
588 $inboxes[$target] = $target;
592 DBA::close($contacts);
598 * Fetches an array of inboxes for the given item and user
600 * @param array $item Item array
601 * @param integer $uid User ID
602 * @param boolean $personal fetch personal inboxes
603 * @param integer $last_id Last item id for adding receivers
604 * @param boolean $forum_mode "true" means that we are sending content to a forum
605 * @return array with inboxes
606 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
607 * @throws \ImagickException
609 public static function fetchTargetInboxes($item, $uid, $personal = false, $last_id = 0, $forum_mode = false)
611 $permissions = self::createPermissionBlockForItem($item, true, $last_id, $forum_mode);
612 if (empty($permissions)) {
618 if ($item['gravity'] == GRAVITY_ACTIVITY) {
619 $item_profile = APContact::getByURL($item['author-link'], false);
621 $item_profile = APContact::getByURL($item['owner-link'], false);
624 foreach (['to', 'cc', 'bto', 'bcc'] as $element) {
625 if (empty($permissions[$element])) {
629 $blindcopy = in_array($element, ['bto', 'bcc']);
631 foreach ($permissions[$element] as $receiver) {
632 if (Network::isUrlBlocked($receiver)) {
636 if ($receiver == $item_profile['followers']) {
637 $inboxes = array_merge($inboxes, self::fetchTargetInboxesforUser($uid, $personal));
639 if (Contact::isLocal($receiver)) {
643 $profile = APContact::getByURL($receiver, false);
644 if (!empty($profile)) {
645 if (empty($profile['sharedinbox']) || $personal || $blindcopy) {
646 $target = $profile['inbox'];
648 $target = $profile['sharedinbox'];
650 if (!self::archivedInbox($target)) {
651 $inboxes[$target] = $target;
662 * Creates an array in the structure of the item table for a given mail id
664 * @param integer $mail_id
669 public static function ItemArrayFromMail($mail_id)
671 $mail = DBA::selectFirst('mail', [], ['id' => $mail_id]);
672 if (!DBA::isResult($mail)) {
676 $reply = DBA::selectFirst('mail', ['uri'], ['parent-uri' => $mail['parent-uri'], 'reply' => false]);
678 // Making the post more compatible for Mastodon by:
679 // - Making it a note and not an article (no title)
680 // - Moving the title into the "summary" field that is used as a "content warning"
681 $mail['body'] = '[abstract]' . $mail['title'] . "[/abstract]\n" . $mail['body'];
684 $mail['author-link'] = $mail['owner-link'] = $mail['from-url'];
685 $mail['allow_cid'] = '<'.$mail['contact-id'].'>';
686 $mail['allow_gid'] = '';
687 $mail['deny_cid'] = '';
688 $mail['deny_gid'] = '';
689 $mail['private'] = true;
690 $mail['deleted'] = false;
691 $mail['edited'] = $mail['created'];
692 $mail['plink'] = $mail['uri'];
693 $mail['thr-parent'] = $reply['uri'];
694 $mail['gravity'] = ($mail['reply'] ? GRAVITY_COMMENT: GRAVITY_PARENT);
696 $mail['event-type'] = '';
697 $mail['attach'] = '';
705 * Creates an activity array for a given mail id
707 * @param integer $mail_id
708 * @param boolean $object_mode Is the activity item is used inside another object?
710 * @return array of activity
713 public static function createActivityFromMail($mail_id, $object_mode = false)
715 $mail = self::ItemArrayFromMail($mail_id);
716 $object = self::createNote($mail);
719 $data = ['@context' => ActivityPub::CONTEXT];
724 $data['id'] = $mail['uri'] . '#Create';
725 $data['type'] = 'Create';
726 $data['actor'] = $mail['author-link'];
727 $data['published'] = DateTimeFormat::utc($mail['created'] . '+00:00', DateTimeFormat::ATOM);
728 $data['instrument'] = self::getService();
729 $data = array_merge($data, self::createPermissionBlockForItem($mail, true));
731 if (empty($data['to']) && !empty($data['cc'])) {
732 $data['to'] = $data['cc'];
735 if (empty($data['to']) && !empty($data['bcc'])) {
736 $data['to'] = $data['bcc'];
742 $object['to'] = $data['to'];
743 $object['tag'] = [['type' => 'Mention', 'href' => $object['to'][0], 'name' => '']];
745 unset($object['cc']);
746 unset($object['bcc']);
748 $data['directMessage'] = true;
750 $data['object'] = $object;
752 $owner = User::getOwnerDataById($mail['uid']);
754 if (!$object_mode && !empty($owner)) {
755 return LDSignature::sign($data, $owner);
762 * Returns the activity type of a given item
766 * @return string with activity type
767 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
768 * @throws \ImagickException
770 private static function getTypeOfItem($item)
774 // Only check for a reshare, if it is a real reshare and no quoted reshare
775 if (strpos($item['body'], "[share") === 0) {
776 $announce = self::getAnnounceArray($item);
777 $reshared = !empty($announce);
782 } elseif ($item['verb'] == Activity::POST) {
783 if ($item['created'] == $item['edited']) {
788 } elseif ($item['verb'] == Activity::LIKE) {
790 } elseif ($item['verb'] == Activity::DISLIKE) {
792 } elseif ($item['verb'] == Activity::ATTEND) {
794 } elseif ($item['verb'] == Activity::ATTENDNO) {
796 } elseif ($item['verb'] == Activity::ATTENDMAYBE) {
797 $type = 'TentativeAccept';
798 } elseif ($item['verb'] == Activity::FOLLOW) {
800 } elseif ($item['verb'] == Activity::TAG) {
810 * Creates the activity or fetches it from the cache
812 * @param integer $item_id
813 * @param boolean $force Force new cache entry
815 * @return array with the activity
818 public static function createCachedActivityFromItem($item_id, $force = false)
820 $cachekey = 'APDelivery:createActivity:' . $item_id;
823 $data = Cache::get($cachekey);
824 if (!is_null($data)) {
829 $data = ActivityPub\Transmitter::createActivityFromItem($item_id);
831 Cache::set($cachekey, $data, Cache::QUARTER_HOUR);
836 * Creates an activity array for a given item id
838 * @param integer $item_id
839 * @param boolean $object_mode Is the activity item is used inside another object?
841 * @return array of activity
844 public static function createActivityFromItem($item_id, $object_mode = false)
846 $item = Item::selectFirst([], ['id' => $item_id, 'parent-network' => Protocol::NATIVE_SUPPORT]);
848 if (!DBA::isResult($item)) {
852 if ($item['wall'] && ($item['uri'] == $item['parent-uri'])) {
853 $owner = User::getOwnerDataById($item['uid']);
854 if (($owner['account-type'] == User::ACCOUNT_TYPE_COMMUNITY) && ($item['author-link'] != $owner['url'])) {
857 // Disguise forum posts as reshares. Will later be converted to a real announce
858 $item['body'] = share_header($item['author-name'], $item['author-link'], $item['author-avatar'],
859 $item['guid'], $item['created'], $item['plink']) . $item['body'] . '[/share]';
864 $condition = ['item-uri' => $item['uri'], 'protocol' => Conversation::PARCEL_ACTIVITYPUB];
865 $conversation = DBA::selectFirst('conversation', ['source'], $condition);
866 if (DBA::isResult($conversation)) {
867 $data = json_decode($conversation['source'], true);
873 $type = self::getTypeOfItem($item);
877 $data = ['@context' => ActivityPub::CONTEXT];
879 if ($item['deleted'] && ($item['gravity'] == GRAVITY_ACTIVITY)) {
881 } elseif ($item['deleted']) {
888 $data['id'] = $item['uri'] . '#' . $type;
889 $data['type'] = $type;
891 if (Item::isForumPost($item) && ($type != 'Announce')) {
892 $data['actor'] = $item['author-link'];
894 $data['actor'] = $item['owner-link'];
897 $data['published'] = DateTimeFormat::utc($item['created'] . '+00:00', DateTimeFormat::ATOM);
899 $data['instrument'] = self::getService();
901 $data = array_merge($data, self::createPermissionBlockForItem($item, false));
903 if (in_array($data['type'], ['Create', 'Update', 'Delete'])) {
904 $data['object'] = self::createNote($item);
905 } elseif ($data['type'] == 'Add') {
906 $data = self::createAddTag($item, $data);
907 } elseif ($data['type'] == 'Announce') {
908 $data = self::createAnnounce($item, $data);
909 } elseif ($data['type'] == 'Follow') {
910 $data['object'] = $item['parent-uri'];
911 } elseif ($data['type'] == 'Undo') {
912 $data['object'] = self::createActivityFromItem($item_id, true);
914 $data['diaspora:guid'] = $item['guid'];
915 if (!empty($item['signed_text'])) {
916 $data['diaspora:like'] = $item['signed_text'];
918 $data['object'] = $item['thr-parent'];
921 if (!empty($item['contact-uid'])) {
922 $uid = $item['contact-uid'];
927 $owner = User::getOwnerDataById($uid);
929 if (!$object_mode && !empty($owner)) {
930 return LDSignature::sign($data, $owner);
935 /// @todo Create "conversation" entry
939 * Creates a location entry for a given item array
943 * @return array with location array
945 private static function createLocation($item)
947 $location = ['type' => 'Place'];
949 if (!empty($item['location'])) {
950 $location['name'] = $item['location'];
955 if (empty($item['coord'])) {
956 $coord = Map::getCoordinates($item['location']);
958 $coords = explode(' ', $item['coord']);
959 if (count($coords) == 2) {
960 $coord = ['lat' => $coords[0], 'lon' => $coords[1]];
964 if (!empty($coord['lat']) && !empty($coord['lon'])) {
965 $location['latitude'] = $coord['lat'];
966 $location['longitude'] = $coord['lon'];
973 * Returns a tag array for a given item array
977 * @return array of tags
978 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
980 private static function createTagList($item)
984 $terms = Term::tagArrayFromItemId($item['id'], [Term::HASHTAG, Term::MENTION, Term::IMPLICIT_MENTION]);
985 foreach ($terms as $term) {
986 if ($term['type'] == Term::HASHTAG) {
987 $url = System::baseUrl() . '/search?tag=' . urlencode($term['term']);
988 $tags[] = ['type' => 'Hashtag', 'href' => $url, 'name' => '#' . $term['term']];
989 } elseif ($term['type'] == Term::MENTION || $term['type'] == Term::IMPLICIT_MENTION) {
990 $contact = Contact::getDetailsByURL($term['url']);
991 if (!empty($contact['addr'])) {
992 $mention = '@' . $contact['addr'];
994 $mention = '@' . $term['url'];
997 $tags[] = ['type' => 'Mention', 'href' => $term['url'], 'name' => $mention];
1001 $announce = self::getAnnounceArray($item);
1002 // Mention the original author upon commented reshares
1003 if (!empty($announce['comment'])) {
1004 $tags[] = ['type' => 'Mention', 'href' => $announce['actor']['url'], 'name' => '@' . $announce['actor']['addr']];
1011 * Adds attachment data to the JSON document
1013 * @param array $item Data of the item that is to be posted
1014 * @param string $type Object type
1016 * @return array with attachment data
1017 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1019 private static function createAttachmentList($item, $type)
1023 // Currently deactivated, since it creates side effects on Mastodon and Pleroma.
1024 // It will be reactivated, once this cleared.
1026 $attach_data = BBCode::getAttachmentData($item['body']);
1027 if (!empty($attach_data['url'])) {
1028 $attachment = ['type' => 'Page',
1029 'mediaType' => 'text/html',
1030 'url' => $attach_data['url']];
1032 if (!empty($attach_data['title'])) {
1033 $attachment['name'] = $attach_data['title'];
1036 if (!empty($attach_data['description'])) {
1037 $attachment['summary'] = $attach_data['description'];
1040 if (!empty($attach_data['image'])) {
1041 $imgdata = Images::getInfoFromURLCached($attach_data['image']);
1043 $attachment['icon'] = ['type' => 'Image',
1044 'mediaType' => $imgdata['mime'],
1045 'width' => $imgdata[0],
1046 'height' => $imgdata[1],
1047 'url' => $attach_data['image']];
1051 $attachments[] = $attachment;
1054 $arr = explode('[/attach],', $item['attach']);
1056 foreach ($arr as $r) {
1058 $cnt = preg_match('|\[attach\]href=\"(.*?)\" length=\"(.*?)\" type=\"(.*?)\" title=\"(.*?)\"|', $r, $matches);
1060 $attributes = ['type' => 'Document',
1061 'mediaType' => $matches[3],
1062 'url' => $matches[1],
1065 if (trim($matches[4]) != '') {
1066 $attributes['name'] = trim($matches[4]);
1069 $attachments[] = $attributes;
1074 if ($type != 'Note') {
1075 return $attachments;
1078 // Simplify image codes
1079 $body = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '[img]$3[/img]', $item['body']);
1081 // Grab all pictures without alternative descriptions and create attachments out of them
1082 if (preg_match_all("/\[img\]([^\[\]]*)\[\/img\]/Usi", $body, $pictures)) {
1083 foreach ($pictures[1] as $picture) {
1084 $imgdata = Images::getInfoFromURLCached($picture);
1086 $attachments[] = ['type' => 'Document',
1087 'mediaType' => $imgdata['mime'],
1094 // Grab all pictures with alternative description and create attachments out of them
1095 if (preg_match_all("/\[img=([^\[\]]*)\]([^\[\]]*)\[\/img\]/Usi", $body, $pictures, PREG_SET_ORDER)) {
1096 foreach ($pictures as $picture) {
1097 $imgdata = Images::getInfoFromURLCached($picture[1]);
1099 $attachments[] = ['type' => 'Document',
1100 'mediaType' => $imgdata['mime'],
1101 'url' => $picture[1],
1102 'name' => $picture[2]];
1107 return $attachments;
1111 * @brief Callback function to replace a Friendica style mention in a mention that is used on AP
1113 * @param array $match Matching values for the callback
1114 * @return string Replaced mention
1115 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1117 private static function mentionCallback($match)
1119 if (empty($match[1])) {
1123 $data = Contact::getDetailsByURL($match[1]);
1124 if (empty($data['nick'])) {
1128 return '@[url=' . $data['url'] . ']' . $data['nick'] . '[/url]';
1132 * Remove image elements since they are added as attachment
1134 * @param string $body
1136 * @return string with removed images
1138 private static function removePictures($body)
1140 // Simplify image codes
1141 $body = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '[img]$3[/img]', $body);
1142 $body = preg_replace("/\[img\=(.*?)\](.*?)\[\/img\]/ism", '[img]$1[/img]', $body);
1144 // Now remove local links
1145 $body = preg_replace_callback(
1146 '/\[url=([^\[\]]*)\]\[img\](.*)\[\/img\]\[\/url\]/Usi',
1148 // We remove the link when it is a link to a local photo page
1149 if (Photo::isLocalPage($match[1])) {
1152 // otherwise we just return the link
1153 return '[url]' . $match[1] . '[/url]';
1158 // Remove all pictures
1159 $body = preg_replace("/\[img\]([^\[\]]*)\[\/img\]/Usi", '', $body);
1165 * Fetches the "context" value for a givem item array from the "conversation" table
1167 * @param array $item
1169 * @return string with context url
1170 * @throws \Exception
1172 private static function fetchContextURLForItem($item)
1174 $conversation = DBA::selectFirst('conversation', ['conversation-href', 'conversation-uri'], ['item-uri' => $item['parent-uri']]);
1175 if (DBA::isResult($conversation) && !empty($conversation['conversation-href'])) {
1176 $context_uri = $conversation['conversation-href'];
1177 } elseif (DBA::isResult($conversation) && !empty($conversation['conversation-uri'])) {
1178 $context_uri = $conversation['conversation-uri'];
1180 $context_uri = $item['parent-uri'] . '#context';
1182 return $context_uri;
1186 * Returns if the post contains sensitive content ("nsfw")
1188 * @param integer $item_id
1191 * @throws \Exception
1193 private static function isSensitive($item_id)
1195 $condition = ['otype' => TERM_OBJ_POST, 'oid' => $item_id, 'type' => TERM_HASHTAG, 'term' => 'nsfw'];
1196 return DBA::exists('term', $condition);
1200 * Creates event data
1202 * @param array $item
1204 * @return array with the event data
1205 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1207 public static function createEvent($item)
1210 $event['name'] = $item['event-summary'];
1211 $event['content'] = BBCode::convert($item['event-desc'], false, 9);
1212 $event['startTime'] = DateTimeFormat::utc($item['event-start'] . '+00:00', DateTimeFormat::ATOM);
1214 if (!$item['event-nofinish']) {
1215 $event['endTime'] = DateTimeFormat::utc($item['event-finish'] . '+00:00', DateTimeFormat::ATOM);
1218 if (!empty($item['event-location'])) {
1219 $item['location'] = $item['event-location'];
1220 $event['location'] = self::createLocation($item);
1227 * Creates a note/article object array
1229 * @param array $item
1231 * @return array with the object data
1232 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1233 * @throws \ImagickException
1235 public static function createNote($item)
1241 if ($item['event-type'] == 'event') {
1243 } elseif (!empty($item['title'])) {
1249 if ($item['deleted']) {
1250 $type = 'Tombstone';
1254 $data['id'] = $item['uri'];
1255 $data['type'] = $type;
1257 if ($item['deleted']) {
1261 $data['summary'] = BBCode::toPlaintext(BBCode::getAbstract($item['body'], Protocol::ACTIVITYPUB));
1263 if ($item['uri'] != $item['thr-parent']) {
1264 $data['inReplyTo'] = $item['thr-parent'];
1266 $data['inReplyTo'] = null;
1269 $data['diaspora:guid'] = $item['guid'];
1270 $data['published'] = DateTimeFormat::utc($item['created'] . '+00:00', DateTimeFormat::ATOM);
1272 if ($item['created'] != $item['edited']) {
1273 $data['updated'] = DateTimeFormat::utc($item['edited'] . '+00:00', DateTimeFormat::ATOM);
1276 $data['url'] = $item['plink'];
1277 $data['attributedTo'] = $item['author-link'];
1278 $data['sensitive'] = self::isSensitive($item['id']);
1279 $data['context'] = self::fetchContextURLForItem($item);
1281 if (!empty($item['title'])) {
1282 $data['name'] = BBCode::toPlaintext($item['title'], false);
1285 $permission_block = self::createPermissionBlockForItem($item, false);
1287 $body = $item['body'];
1289 if (empty($item['uid']) || !Feature::isEnabled($item['uid'], 'explicit_mentions')) {
1290 $body = self::prependMentions($body, $permission_block);
1293 if ($type == 'Note') {
1294 $body = self::removePictures($body);
1295 } elseif (($type == 'Article') && empty($data['summary'])) {
1296 $data['summary'] = BBCode::toPlaintext(Plaintext::shorten(self::removePictures($body), 1000));
1299 if ($type == 'Event') {
1300 $data = array_merge($data, self::createEvent($item));
1302 $regexp = "/[@!]\[url\=([^\[\]]*)\].*?\[\/url\]/ism";
1303 $body = preg_replace_callback($regexp, ['self', 'mentionCallback'], $body);
1305 $data['content'] = BBCode::convert($body, false, 9);
1308 $regexp = "/[@!]\[url\=([^\[\]]*)\].*?\[\/url\]/ism";
1309 $richbody = preg_replace_callback($regexp, ['self', 'mentionCallback'], $item['body']);
1310 $richbody = BBCode::removeAttachment($richbody);
1312 $data['contentMap']['text/html'] = BBCode::convert($richbody, false);
1313 $data['contentMap']['text/markdown'] = BBCode::toMarkdown($item["body"]);
1315 $data['source'] = ['content' => $item['body'], 'mediaType' => "text/bbcode"];
1317 if (!empty($item['signed_text']) && ($item['uri'] != $item['thr-parent'])) {
1318 $data['diaspora:comment'] = $item['signed_text'];
1321 $data['attachment'] = self::createAttachmentList($item, $type);
1322 $data['tag'] = self::createTagList($item);
1324 if (empty($data['location']) && (!empty($item['coord']) || !empty($item['location']))) {
1325 $data['location'] = self::createLocation($item);
1328 if (!empty($item['app'])) {
1329 $data['generator'] = ['type' => 'Application', 'name' => $item['app']];
1332 $data = array_merge($data, $permission_block);
1338 * Creates an an "add tag" entry
1340 * @param array $item
1341 * @param array $data activity data
1343 * @return array with activity data for adding tags
1344 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1345 * @throws \ImagickException
1347 private static function createAddTag($item, $data)
1349 $object = XML::parseString($item['object'], false);
1350 $target = XML::parseString($item["target"], false);
1352 $data['diaspora:guid'] = $item['guid'];
1353 $data['actor'] = $item['author-link'];
1354 $data['target'] = (string)$target->id;
1355 $data['summary'] = BBCode::toPlaintext($item['body']);
1356 $data['object'] = ['id' => (string)$object->id, 'type' => 'tag', 'name' => (string)$object->title, 'content' => (string)$object->content];
1362 * Creates an announce object entry
1364 * @param array $item
1365 * @param array $data activity data
1367 * @return array with activity data
1368 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1369 * @throws \ImagickException
1371 private static function createAnnounce($item, $data)
1373 $orig_body = $item['body'];
1374 $announce = self::getAnnounceArray($item);
1375 if (empty($announce)) {
1376 $data['type'] = 'Create';
1377 $data['object'] = self::createNote($item);
1381 if (empty($announce['comment'])) {
1382 // Pure announce, without a quote
1383 $data['type'] = 'Announce';
1384 $data['object'] = $announce['object']['uri'];
1389 $data['type'] = 'Create';
1390 $item['body'] = $announce['comment'] . "\n" . $announce['object']['plink'];
1391 $data['object'] = self::createNote($item);
1393 /// @todo Finally descide how to implement this in AP. This is a possible way:
1394 $data['object']['attachment'][] = self::createNote($announce['object']);
1396 $data['object']['source']['content'] = $orig_body;
1401 * Return announce related data if the item is an annunce
1403 * @param array $item
1407 public static function getAnnounceArray($item)
1409 $reshared = Item::getShareArray($item);
1410 if (empty($reshared['guid'])) {
1414 $reshared_item = Item::selectFirst([], ['guid' => $reshared['guid']]);
1415 if (!DBA::isResult($reshared_item)) {
1419 if (!in_array($reshared_item['network'], [Protocol::ACTIVITYPUB, Protocol::DFRN])) {
1423 $profile = APContact::getByURL($reshared_item['author-link'], false);
1424 if (empty($profile)) {
1428 return ['object' => $reshared_item, 'actor' => $profile, 'comment' => $reshared['comment']];
1432 * Checks if the provided item array is an announce
1434 * @param array $item
1438 public static function isAnnounce($item)
1440 $announce = self::getAnnounceArray($item);
1441 if (empty($announce)) {
1445 return empty($announce['comment']);
1449 * Creates an activity id for a given contact id
1451 * @param integer $cid Contact ID of target
1453 * @return bool|string activity id
1455 public static function activityIDFromContact($cid)
1457 $contact = DBA::selectFirst('contact', ['uid', 'id', 'created'], ['id' => $cid]);
1458 if (!DBA::isResult($contact)) {
1462 $hash = hash('ripemd128', $contact['uid'].'-'.$contact['id'].'-'.$contact['created']);
1463 $uuid = substr($hash, 0, 8). '-' . substr($hash, 8, 4) . '-' . substr($hash, 12, 4) . '-' . substr($hash, 16, 4) . '-' . substr($hash, 20, 12);
1464 return System::baseUrl() . '/activity/' . $uuid;
1468 * Transmits a contact suggestion to a given inbox
1470 * @param integer $uid User ID
1471 * @param string $inbox Target inbox
1472 * @param integer $suggestion_id Suggestion ID
1474 * @return boolean was the transmission successful?
1475 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1477 public static function sendContactSuggestion($uid, $inbox, $suggestion_id)
1479 $owner = User::getOwnerDataById($uid);
1481 $suggestion = DBA::selectFirst('fsuggest', ['url', 'note', 'created'], ['id' => $suggestion_id]);
1483 $data = ['@context' => ActivityPub::CONTEXT,
1484 'id' => System::baseUrl() . '/activity/' . System::createGUID(),
1485 'type' => 'Announce',
1486 'actor' => $owner['url'],
1487 'object' => $suggestion['url'],
1488 'content' => $suggestion['note'],
1489 'instrument' => self::getService(),
1490 'to' => [ActivityPub::PUBLIC_COLLECTION],
1493 $signed = LDSignature::sign($data, $owner);
1495 Logger::log('Deliver profile deletion for user ' . $uid . ' to ' . $inbox . ' via ActivityPub', Logger::DEBUG);
1496 return HTTPSignature::transmit($signed, $inbox, $uid);
1500 * Transmits a profile relocation to a given inbox
1502 * @param integer $uid User ID
1503 * @param string $inbox Target inbox
1505 * @return boolean was the transmission successful?
1506 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1508 public static function sendProfileRelocation($uid, $inbox)
1510 $owner = User::getOwnerDataById($uid);
1512 $data = ['@context' => ActivityPub::CONTEXT,
1513 'id' => System::baseUrl() . '/activity/' . System::createGUID(),
1514 'type' => 'dfrn:relocate',
1515 'actor' => $owner['url'],
1516 'object' => $owner['url'],
1517 'published' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
1518 'instrument' => self::getService(),
1519 'to' => [ActivityPub::PUBLIC_COLLECTION],
1522 $signed = LDSignature::sign($data, $owner);
1524 Logger::log('Deliver profile relocation for user ' . $uid . ' to ' . $inbox . ' via ActivityPub', Logger::DEBUG);
1525 return HTTPSignature::transmit($signed, $inbox, $uid);
1529 * Transmits a profile deletion to a given inbox
1531 * @param integer $uid User ID
1532 * @param string $inbox Target inbox
1534 * @return boolean was the transmission successful?
1535 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1537 public static function sendProfileDeletion($uid, $inbox)
1539 $owner = User::getOwnerDataById($uid);
1541 if (empty($owner)) {
1542 Logger::error('No owner data found, the deletion message cannot be processed.', ['user' => $uid]);
1546 if (empty($owner['uprvkey'])) {
1547 Logger::error('No private key for owner found, the deletion message cannot be processed.', ['user' => $uid]);
1551 $data = ['@context' => ActivityPub::CONTEXT,
1552 'id' => System::baseUrl() . '/activity/' . System::createGUID(),
1554 'actor' => $owner['url'],
1555 'object' => $owner['url'],
1556 'published' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
1557 'instrument' => self::getService(),
1558 'to' => [ActivityPub::PUBLIC_COLLECTION],
1561 $signed = LDSignature::sign($data, $owner);
1563 Logger::log('Deliver profile deletion for user ' . $uid . ' to ' . $inbox . ' via ActivityPub', Logger::DEBUG);
1564 return HTTPSignature::transmit($signed, $inbox, $uid);
1568 * Transmits a profile change to a given inbox
1570 * @param integer $uid User ID
1571 * @param string $inbox Target inbox
1573 * @return boolean was the transmission successful?
1574 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1575 * @throws \ImagickException
1577 public static function sendProfileUpdate($uid, $inbox)
1579 $owner = User::getOwnerDataById($uid);
1580 $profile = APContact::getByURL($owner['url']);
1582 $data = ['@context' => ActivityPub::CONTEXT,
1583 'id' => System::baseUrl() . '/activity/' . System::createGUID(),
1585 'actor' => $owner['url'],
1586 'object' => self::getProfile($uid),
1587 'published' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
1588 'instrument' => self::getService(),
1589 'to' => [$profile['followers']],
1592 $signed = LDSignature::sign($data, $owner);
1594 Logger::log('Deliver profile update for user ' . $uid . ' to ' . $inbox . ' via ActivityPub', Logger::DEBUG);
1595 return HTTPSignature::transmit($signed, $inbox, $uid);
1599 * Transmits a given activity to a target
1601 * @param string $activity Type name
1602 * @param string $target Target profile
1603 * @param integer $uid User ID
1605 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1606 * @throws \ImagickException
1607 * @throws \Exception
1609 public static function sendActivity($activity, $target, $uid, $id = '')
1611 $profile = APContact::getByURL($target);
1612 if (empty($profile['inbox'])) {
1613 Logger::warning('No inbox found for target', ['target' => $target, 'profile' => $profile]);
1617 $owner = User::getOwnerDataById($uid);
1620 $id = System::baseUrl() . '/activity/' . System::createGUID();
1623 $data = ['@context' => ActivityPub::CONTEXT,
1625 'type' => $activity,
1626 'actor' => $owner['url'],
1627 'object' => $profile['url'],
1628 'instrument' => self::getService(),
1629 'to' => [$profile['url']]];
1631 Logger::log('Sending activity ' . $activity . ' to ' . $target . ' for user ' . $uid, Logger::DEBUG);
1633 $signed = LDSignature::sign($data, $owner);
1634 return HTTPSignature::transmit($signed, $profile['inbox'], $uid);
1638 * Transmits a "follow object" activity to a target
1639 * This is a preparation for sending automated "follow" requests when receiving "Announce" messages
1641 * @param string $object Object URL
1642 * @param string $target Target profile
1643 * @param integer $uid User ID
1645 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1646 * @throws \ImagickException
1647 * @throws \Exception
1649 public static function sendFollowObject($object, $target, $uid = 0)
1651 $profile = APContact::getByURL($target);
1652 if (empty($profile['inbox'])) {
1653 Logger::warning('No inbox found for target', ['target' => $target, 'profile' => $profile]);
1658 // Fetch the list of administrators
1659 $admin_mail = explode(',', str_replace(' ', '', Config::get('config', 'admin_email')));
1661 // We need to use some user as a sender. It doesn't care who it will send. We will use an administrator account.
1662 $condition = ['verified' => true, 'blocked' => false, 'account_removed' => false, 'account_expired' => false, 'email' => $admin_mail];
1663 $first_user = DBA::selectFirst('user', ['uid'], $condition);
1664 $uid = $first_user['uid'];
1667 $condition = ['verb' => Activity::FOLLOW, 'uid' => 0, 'parent-uri' => $object,
1668 'author-id' => Contact::getPublicIdByUserId($uid)];
1669 if (Item::exists($condition)) {
1670 Logger::log('Follow for ' . $object . ' for user ' . $uid . ' does already exist.', Logger::DEBUG);
1674 $owner = User::getOwnerDataById($uid);
1676 $data = ['@context' => ActivityPub::CONTEXT,
1677 'id' => System::baseUrl() . '/activity/' . System::createGUID(),
1679 'actor' => $owner['url'],
1680 'object' => $object,
1681 'instrument' => self::getService(),
1682 'to' => [$profile['url']]];
1684 Logger::log('Sending follow ' . $object . ' to ' . $target . ' for user ' . $uid, Logger::DEBUG);
1686 $signed = LDSignature::sign($data, $owner);
1687 return HTTPSignature::transmit($signed, $profile['inbox'], $uid);
1691 * Transmit a message that the contact request had been accepted
1693 * @param string $target Target profile
1695 * @param integer $uid User ID
1696 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1697 * @throws \ImagickException
1699 public static function sendContactAccept($target, $id, $uid)
1701 $profile = APContact::getByURL($target);
1702 if (empty($profile['inbox'])) {
1703 Logger::warning('No inbox found for target', ['target' => $target, 'profile' => $profile]);
1707 $owner = User::getOwnerDataById($uid);
1708 $data = ['@context' => ActivityPub::CONTEXT,
1709 'id' => System::baseUrl() . '/activity/' . System::createGUID(),
1711 'actor' => $owner['url'],
1713 'id' => (string)$id,
1715 'actor' => $profile['url'],
1716 'object' => $owner['url']
1718 'instrument' => self::getService(),
1719 'to' => [$profile['url']]];
1721 Logger::debug('Sending accept to ' . $target . ' for user ' . $uid . ' with id ' . $id);
1723 $signed = LDSignature::sign($data, $owner);
1724 HTTPSignature::transmit($signed, $profile['inbox'], $uid);
1728 * Reject a contact request or terminates the contact relation
1730 * @param string $target Target profile
1732 * @param integer $uid User ID
1733 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1734 * @throws \ImagickException
1736 public static function sendContactReject($target, $id, $uid)
1738 $profile = APContact::getByURL($target);
1739 if (empty($profile['inbox'])) {
1740 Logger::warning('No inbox found for target', ['target' => $target, 'profile' => $profile]);
1744 $owner = User::getOwnerDataById($uid);
1745 $data = ['@context' => ActivityPub::CONTEXT,
1746 'id' => System::baseUrl() . '/activity/' . System::createGUID(),
1748 'actor' => $owner['url'],
1750 'id' => (string)$id,
1752 'actor' => $profile['url'],
1753 'object' => $owner['url']
1755 'instrument' => self::getService(),
1756 'to' => [$profile['url']]];
1758 Logger::debug('Sending reject to ' . $target . ' for user ' . $uid . ' with id ' . $id);
1760 $signed = LDSignature::sign($data, $owner);
1761 HTTPSignature::transmit($signed, $profile['inbox'], $uid);
1765 * Transmits a message that we don't want to follow this contact anymore
1767 * @param string $target Target profile
1768 * @param integer $uid User ID
1769 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1770 * @throws \ImagickException
1771 * @throws \Exception
1773 public static function sendContactUndo($target, $cid, $uid)
1775 $profile = APContact::getByURL($target);
1776 if (empty($profile['inbox'])) {
1777 Logger::warning('No inbox found for target', ['target' => $target, 'profile' => $profile]);
1781 $object_id = self::activityIDFromContact($cid);
1782 if (empty($object_id)) {
1786 $id = System::baseUrl() . '/activity/' . System::createGUID();
1788 $owner = User::getOwnerDataById($uid);
1789 $data = ['@context' => ActivityPub::CONTEXT,
1792 'actor' => $owner['url'],
1793 'object' => ['id' => $object_id, 'type' => 'Follow',
1794 'actor' => $owner['url'],
1795 'object' => $profile['url']],
1796 'instrument' => self::getService(),
1797 'to' => [$profile['url']]];
1799 Logger::log('Sending undo to ' . $target . ' for user ' . $uid . ' with id ' . $id, Logger::DEBUG);
1801 $signed = LDSignature::sign($data, $owner);
1802 HTTPSignature::transmit($signed, $profile['inbox'], $uid);
1805 private static function prependMentions($body, array $permission_block)
1807 if (Config::get('system', 'disable_implicit_mentions')) {
1813 foreach ($permission_block['to'] as $profile_url) {
1814 $profile = Contact::getDetailsByURL($profile_url);
1815 if (!empty($profile['addr'])
1816 && $profile['contact-type'] != Contact::TYPE_COMMUNITY
1817 && !strstr($body, $profile['addr'])
1818 && !strstr($body, $profile_url)
1820 $mentions[] = '@[url=' . $profile_url . ']' . $profile['nick'] . '[/url]';
1824 $mentions[] = $body;
1826 return implode(' ', $mentions);