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;
17 use Friendica\Model\APContact;
18 use Friendica\Model\Contact;
19 use Friendica\Model\Conversation;
20 use Friendica\Model\Item;
21 use Friendica\Model\Profile;
22 use Friendica\Model\Photo;
23 use Friendica\Model\Term;
24 use Friendica\Model\User;
25 use Friendica\Protocol\Activity;
26 use Friendica\Protocol\ActivityPub;
27 use Friendica\Util\DateTimeFormat;
28 use Friendica\Util\HTTPSignature;
29 use Friendica\Util\Images;
30 use Friendica\Util\JsonLD;
31 use Friendica\Util\LDSignature;
32 use Friendica\Util\Map;
33 use Friendica\Util\Network;
34 use Friendica\Util\XML;
36 require_once 'include/api.php';
37 require_once 'mod/share.php';
40 * @brief ActivityPub Transmitter Protocol class
48 * collects the lost of followers of the given owner
50 * @param array $owner Owner array
51 * @param integer $page Page number
53 * @return array of owners
54 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
56 public static function getFollowers($owner, $page = null)
58 $condition = ['rel' => [Contact::FOLLOWER, Contact::FRIEND], 'network' => Protocol::NATIVE_SUPPORT, 'uid' => $owner['uid'],
59 'self' => false, 'deleted' => false, 'hidden' => false, 'archive' => false, 'pending' => false];
60 $count = DBA::count('contact', $condition);
62 $data = ['@context' => ActivityPub::CONTEXT];
63 $data['id'] = System::baseUrl() . '/followers/' . $owner['nickname'];
64 $data['type'] = 'OrderedCollection';
65 $data['totalItems'] = $count;
67 // When we hide our friends we will only show the pure number but don't allow more.
68 $profile = Profile::getByUID($owner['uid']);
69 if (!empty($profile['hide-friends'])) {
74 $data['first'] = System::baseUrl() . '/followers/' . $owner['nickname'] . '?page=1';
76 $data['type'] = 'OrderedCollectionPage';
79 $contacts = DBA::select('contact', ['url'], $condition, ['limit' => [($page - 1) * 100, 100]]);
80 while ($contact = DBA::fetch($contacts)) {
81 $list[] = $contact['url'];
85 $data['next'] = System::baseUrl() . '/followers/' . $owner['nickname'] . '?page=' . ($page + 1);
88 $data['partOf'] = System::baseUrl() . '/followers/' . $owner['nickname'];
90 $data['orderedItems'] = $list;
97 * Create list of following contacts
99 * @param array $owner Owner array
100 * @param integer $page Page numbe
102 * @return array of following contacts
103 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
105 public static function getFollowing($owner, $page = null)
107 $condition = ['rel' => [Contact::SHARING, Contact::FRIEND], 'network' => Protocol::NATIVE_SUPPORT, 'uid' => $owner['uid'],
108 'self' => false, 'deleted' => false, 'hidden' => false, 'archive' => false, 'pending' => false];
109 $count = DBA::count('contact', $condition);
111 $data = ['@context' => ActivityPub::CONTEXT];
112 $data['id'] = System::baseUrl() . '/following/' . $owner['nickname'];
113 $data['type'] = 'OrderedCollection';
114 $data['totalItems'] = $count;
116 // When we hide our friends we will only show the pure number but don't allow more.
117 $profile = Profile::getByUID($owner['uid']);
118 if (!empty($profile['hide-friends'])) {
123 $data['first'] = System::baseUrl() . '/following/' . $owner['nickname'] . '?page=1';
125 $data['type'] = 'OrderedCollectionPage';
128 $contacts = DBA::select('contact', ['url'], $condition, ['limit' => [($page - 1) * 100, 100]]);
129 while ($contact = DBA::fetch($contacts)) {
130 $list[] = $contact['url'];
134 $data['next'] = System::baseUrl() . '/following/' . $owner['nickname'] . '?page=' . ($page + 1);
137 $data['partOf'] = System::baseUrl() . '/following/' . $owner['nickname'];
139 $data['orderedItems'] = $list;
146 * Public posts for the given owner
148 * @param array $owner Owner array
149 * @param integer $page Page numbe
151 * @return array of posts
152 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
153 * @throws \ImagickException
155 public static function getOutbox($owner, $page = null)
157 $public_contact = Contact::getIdForURL($owner['url'], 0, true);
159 $condition = ['uid' => 0, 'contact-id' => $public_contact, 'author-id' => $public_contact,
160 'private' => false, 'gravity' => [GRAVITY_PARENT, GRAVITY_COMMENT],
161 'deleted' => false, 'visible' => true, 'moderated' => false];
162 $count = DBA::count('item', $condition);
164 $data = ['@context' => ActivityPub::CONTEXT];
165 $data['id'] = System::baseUrl() . '/outbox/' . $owner['nickname'];
166 $data['type'] = 'OrderedCollection';
167 $data['totalItems'] = $count;
170 $data['first'] = System::baseUrl() . '/outbox/' . $owner['nickname'] . '?page=1';
172 $data['type'] = 'OrderedCollectionPage';
175 $condition['parent-network'] = Protocol::NATIVE_SUPPORT;
177 $items = Item::select(['id'], $condition, ['limit' => [($page - 1) * 20, 20], 'order' => ['created' => true]]);
178 while ($item = Item::fetch($items)) {
179 $activity = self::createActivityFromItem($item['id'], true);
180 // Only list "Create" activity objects here, no reshares
181 if (is_array($activity['object']) && ($activity['type'] == 'Create')) {
182 $list[] = $activity['object'];
187 $data['next'] = System::baseUrl() . '/outbox/' . $owner['nickname'] . '?page=' . ($page + 1);
190 $data['partOf'] = System::baseUrl() . '/outbox/' . $owner['nickname'];
192 $data['orderedItems'] = $list;
199 * Return the service array containing information the used software and it's url
201 * @return array with service data
203 private static function getService()
205 return ['type' => 'Service',
206 'name' => FRIENDICA_PLATFORM . " '" . FRIENDICA_CODENAME . "' " . FRIENDICA_VERSION . '-' . DB_UPDATE_VERSION,
207 'url' => BaseObject::getApp()->getBaseURL()];
211 * Return the ActivityPub profile of the given user
213 * @param integer $uid User ID
214 * @return array with profile data
215 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
217 public static function getProfile($uid)
219 $condition = ['uid' => $uid, 'blocked' => false, 'account_expired' => false,
220 'account_removed' => false, 'verified' => true];
221 $fields = ['guid', 'nickname', 'pubkey', 'account-type', 'page-flags'];
222 $user = DBA::selectFirst('user', $fields, $condition);
223 if (!DBA::isResult($user)) {
227 $fields = ['locality', 'region', 'country-name'];
228 $profile = DBA::selectFirst('profile', $fields, ['uid' => $uid, 'is-default' => true]);
229 if (!DBA::isResult($profile)) {
233 $fields = ['name', 'url', 'location', 'about', 'avatar', 'photo'];
234 $contact = DBA::selectFirst('contact', $fields, ['uid' => $uid, 'self' => true]);
235 if (!DBA::isResult($contact)) {
239 $data = ['@context' => ActivityPub::CONTEXT];
240 $data['id'] = $contact['url'];
241 $data['diaspora:guid'] = $user['guid'];
242 $data['type'] = ActivityPub::ACCOUNT_TYPES[$user['account-type']];
243 $data['following'] = System::baseUrl() . '/following/' . $user['nickname'];
244 $data['followers'] = System::baseUrl() . '/followers/' . $user['nickname'];
245 $data['inbox'] = System::baseUrl() . '/inbox/' . $user['nickname'];
246 $data['outbox'] = System::baseUrl() . '/outbox/' . $user['nickname'];
247 $data['preferredUsername'] = $user['nickname'];
248 $data['name'] = $contact['name'];
249 $data['vcard:hasAddress'] = ['@type' => 'vcard:Home', 'vcard:country-name' => $profile['country-name'],
250 'vcard:region' => $profile['region'], 'vcard:locality' => $profile['locality']];
251 $data['summary'] = $contact['about'];
252 $data['url'] = $contact['url'];
253 $data['manuallyApprovesFollowers'] = in_array($user['page-flags'], [User::PAGE_FLAGS_NORMAL, User::PAGE_FLAGS_PRVGROUP]);
254 $data['publicKey'] = ['id' => $contact['url'] . '#main-key',
255 'owner' => $contact['url'],
256 'publicKeyPem' => $user['pubkey']];
257 $data['endpoints'] = ['sharedInbox' => System::baseUrl() . '/inbox'];
258 $data['icon'] = ['type' => 'Image',
259 'url' => $contact['photo']];
261 $data['generator'] = self::getService();
263 // tags: https://kitty.town/@inmysocks/100656097926961126.json
268 * @param string $username
270 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
272 public static function getDeletedUser($username)
275 '@context' => ActivityPub::CONTEXT,
276 'id' => System::baseUrl() . '/profile/' . $username,
277 'type' => 'Tombstone',
278 'published' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
279 'updated' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
280 'deleted' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
285 * Returns an array with permissions of a given item array
289 * @return array with permissions
290 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
291 * @throws \ImagickException
293 private static function fetchPermissionBlockFromConversation($item)
295 if (empty($item['thr-parent'])) {
299 $condition = ['item-uri' => $item['thr-parent'], 'protocol' => Conversation::PARCEL_ACTIVITYPUB];
300 $conversation = DBA::selectFirst('conversation', ['source'], $condition);
301 if (!DBA::isResult($conversation)) {
305 $activity = json_decode($conversation['source'], true);
307 $actor = JsonLD::fetchElement($activity, 'actor', 'id');
308 $profile = APContact::getByURL($actor);
310 $item_profile = APContact::getByURL($item['author-link']);
311 $exclude[] = $item['author-link'];
313 if ($item['gravity'] == GRAVITY_PARENT) {
314 $exclude[] = $item['owner-link'];
317 $permissions['to'][] = $actor;
319 foreach (['to', 'cc', 'bto', 'bcc'] as $element) {
320 if (empty($activity[$element])) {
323 if (is_string($activity[$element])) {
324 $activity[$element] = [$activity[$element]];
327 foreach ($activity[$element] as $receiver) {
328 if ($receiver == $profile['followers'] && !empty($item_profile['followers'])) {
329 $permissions[$element][] = $item_profile['followers'];
330 } elseif (!in_array($receiver, $exclude)) {
331 $permissions[$element][] = $receiver;
339 * Creates an array of permissions from an item thread
341 * @param array $item Item array
342 * @param boolean $blindcopy addressing via "bcc" or "cc"?
343 * @param integer $last_id Last item id for adding receivers
344 * @param boolean $forum_mode "true" means that we are sending content to a forum
346 * @return array with permission data
347 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
348 * @throws \ImagickException
350 private static function createPermissionBlockForItem($item, $blindcopy, $last_id = 0, $forum_mode = false)
353 $last_id = $item['id'];
358 // Check if we should always deliver our stuff via BCC
359 if (!empty($item['uid'])) {
360 $profile = Profile::getByUID($item['uid']);
361 if (!empty($profile)) {
362 $always_bcc = $profile['hide-friends'];
366 if (Config::get('debug', 'total_ap_delivery')) {
367 // Will be activated in a later step
368 $networks = Protocol::FEDERATED;
370 // For now only send to these contacts:
371 $networks = [Protocol::ACTIVITYPUB, Protocol::OSTATUS];
374 $data = ['to' => [], 'cc' => [], 'bcc' => []];
376 if ($item['gravity'] == GRAVITY_PARENT) {
377 $actor_profile = APContact::getByURL($item['owner-link']);
379 $actor_profile = APContact::getByURL($item['author-link']);
382 $terms = Term::tagArrayFromItemId($item['id'], [Term::MENTION, Term::IMPLICIT_MENTION]);
384 // Directly mention the original author upon a quoted reshare.
385 // Else just ensure that the original author receives the reshare.
386 $announce = self::getAnnounceObject($item);
387 if (!empty($announce['comment'])) {
388 $data['to'][] = $announce['actor']['url'];
389 } elseif (!empty($announce)) {
390 $data['cc'][] = $announce['actor']['url'];
393 if (!$item['private']) {
394 $data = array_merge($data, self::fetchPermissionBlockFromConversation($item));
396 $data['to'][] = ActivityPub::PUBLIC_COLLECTION;
398 foreach ($terms as $term) {
399 $profile = APContact::getByURL($term['url'], false);
400 if (!empty($profile)) {
401 $data['to'][] = $profile['url'];
405 $receiver_list = Item::enumeratePermissions($item, true);
407 foreach ($terms as $term) {
408 $cid = Contact::getIdForURL($term['url'], $item['uid']);
409 if (!empty($cid) && in_array($cid, $receiver_list)) {
410 $contact = DBA::selectFirst('contact', ['url', 'network', 'protocol'], ['id' => $cid]);
411 if (!DBA::isResult($contact) || (!in_array($contact['network'], $networks) && ($contact['protocol'] != Protocol::ACTIVITYPUB))) {
415 if (!empty($profile = APContact::getByURL($contact['url'], false))) {
416 $data['to'][] = $profile['url'];
421 foreach ($receiver_list as $receiver) {
422 $contact = DBA::selectFirst('contact', ['url', 'hidden', 'network', 'protocol'], ['id' => $receiver]);
423 if (!DBA::isResult($contact) || (!in_array($contact['network'], $networks) && ($contact['protocol'] != Protocol::ACTIVITYPUB))) {
427 if (!empty($profile = APContact::getByURL($contact['url'], false))) {
428 if ($contact['hidden'] || $always_bcc) {
429 $data['bcc'][] = $profile['url'];
431 $data['cc'][] = $profile['url'];
437 if (!empty($item['parent'])) {
438 $parents = Item::select(['id', 'author-link', 'owner-link', 'gravity', 'uri'], ['parent' => $item['parent']]);
439 while ($parent = Item::fetch($parents)) {
440 if ($parent['gravity'] == GRAVITY_PARENT) {
441 $profile = APContact::getByURL($parent['owner-link'], false);
442 if (!empty($profile)) {
443 if ($item['gravity'] != GRAVITY_PARENT) {
444 // Comments to forums are directed to the forum
445 // But comments to forums aren't directed to the followers collection
446 if ($profile['type'] == 'Group') {
447 $data['to'][] = $profile['url'];
449 $data['cc'][] = $profile['url'];
450 if (!$item['private'] && !empty($actor_profile['followers'])) {
451 $data['cc'][] = $actor_profile['followers'];
455 // Public thread parent post always are directed to the followers
456 if (!$item['private'] && !$forum_mode) {
457 $data['cc'][] = $actor_profile['followers'];
463 // Don't include data from future posts
464 if ($parent['id'] >= $last_id) {
468 $profile = APContact::getByURL($parent['author-link'], false);
469 if (!empty($profile)) {
470 if (($profile['type'] == 'Group') || ($parent['uri'] == $item['thr-parent'])) {
471 $data['to'][] = $profile['url'];
473 $data['cc'][] = $profile['url'];
477 DBA::close($parents);
480 $data['to'] = array_unique($data['to']);
481 $data['cc'] = array_unique($data['cc']);
482 $data['bcc'] = array_unique($data['bcc']);
484 if (($key = array_search($item['author-link'], $data['to'])) !== false) {
485 unset($data['to'][$key]);
488 if (($key = array_search($item['author-link'], $data['cc'])) !== false) {
489 unset($data['cc'][$key]);
492 if (($key = array_search($item['author-link'], $data['bcc'])) !== false) {
493 unset($data['bcc'][$key]);
496 foreach ($data['to'] as $to) {
497 if (($key = array_search($to, $data['cc'])) !== false) {
498 unset($data['cc'][$key]);
501 if (($key = array_search($to, $data['bcc'])) !== false) {
502 unset($data['bcc'][$key]);
506 foreach ($data['cc'] as $cc) {
507 if (($key = array_search($cc, $data['bcc'])) !== false) {
508 unset($data['bcc'][$key]);
512 $receivers = ['to' => array_values($data['to']), 'cc' => array_values($data['cc']), 'bcc' => array_values($data['bcc'])];
515 unset($receivers['bcc']);
522 * Check if an inbox is archived
524 * @param string $url Inbox url
526 * @return boolean "true" if inbox is archived
528 private static function archivedInbox($url)
530 return DBA::exists('inbox-status', ['url' => $url, 'archive' => true]);
534 * Fetches a list of inboxes of followers of a given user
536 * @param integer $uid User ID
537 * @param boolean $personal fetch personal inboxes
539 * @return array of follower inboxes
540 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
541 * @throws \ImagickException
543 public static function fetchTargetInboxesforUser($uid, $personal = false)
547 if (Config::get('debug', 'total_ap_delivery')) {
548 // Will be activated in a later step
549 $networks = Protocol::FEDERATED;
551 // For now only send to these contacts:
552 $networks = [Protocol::ACTIVITYPUB, Protocol::OSTATUS];
555 $condition = ['uid' => $uid, 'archive' => false, 'pending' => false];
558 $condition['rel'] = [Contact::FOLLOWER, Contact::FRIEND];
561 $contacts = DBA::select('contact', ['url', 'network', 'protocol'], $condition);
562 while ($contact = DBA::fetch($contacts)) {
563 if (Contact::isLocal($contact['url'])) {
567 if (!in_array($contact['network'], $networks) && ($contact['protocol'] != Protocol::ACTIVITYPUB)) {
571 if (Network::isUrlBlocked($contact['url'])) {
575 $profile = APContact::getByURL($contact['url'], false);
576 if (!empty($profile)) {
577 if (empty($profile['sharedinbox']) || $personal) {
578 $target = $profile['inbox'];
580 $target = $profile['sharedinbox'];
582 if (!self::archivedInbox($target)) {
583 $inboxes[$target] = $target;
587 DBA::close($contacts);
593 * Fetches an array of inboxes for the given item and user
595 * @param array $item Item array
596 * @param integer $uid User ID
597 * @param boolean $personal fetch personal inboxes
598 * @param integer $last_id Last item id for adding receivers
599 * @param boolean $forum_mode "true" means that we are sending content to a forum
600 * @return array with inboxes
601 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
602 * @throws \ImagickException
604 public static function fetchTargetInboxes($item, $uid, $personal = false, $last_id = 0, $forum_mode = false)
606 $permissions = self::createPermissionBlockForItem($item, true, $last_id, $forum_mode);
607 if (empty($permissions)) {
613 if ($item['gravity'] == GRAVITY_ACTIVITY) {
614 $item_profile = APContact::getByURL($item['author-link'], false);
616 $item_profile = APContact::getByURL($item['owner-link'], false);
619 foreach (['to', 'cc', 'bto', 'bcc'] as $element) {
620 if (empty($permissions[$element])) {
624 $blindcopy = in_array($element, ['bto', 'bcc']);
626 foreach ($permissions[$element] as $receiver) {
627 if (Network::isUrlBlocked($receiver)) {
631 if ($receiver == $item_profile['followers']) {
632 $inboxes = array_merge($inboxes, self::fetchTargetInboxesforUser($uid, $personal));
634 if (Contact::isLocal($receiver)) {
638 $profile = APContact::getByURL($receiver, false);
639 if (!empty($profile)) {
640 if (empty($profile['sharedinbox']) || $personal || $blindcopy) {
641 $target = $profile['inbox'];
643 $target = $profile['sharedinbox'];
645 if (!self::archivedInbox($target)) {
646 $inboxes[$target] = $target;
657 * Creates an array in the structure of the item table for a given mail id
659 * @param integer $mail_id
664 public static function ItemArrayFromMail($mail_id)
666 $mail = DBA::selectFirst('mail', [], ['id' => $mail_id]);
667 if (!DBA::isResult($mail)) {
671 $reply = DBA::selectFirst('mail', ['uri'], ['parent-uri' => $mail['parent-uri'], 'reply' => false]);
673 // Making the post more compatible for Mastodon by:
674 // - Making it a note and not an article (no title)
675 // - Moving the title into the "summary" field that is used as a "content warning"
676 $mail['body'] = '[abstract]' . $mail['title'] . "[/abstract]\n" . $mail['body'];
679 $mail['author-link'] = $mail['owner-link'] = $mail['from-url'];
680 $mail['allow_cid'] = '<'.$mail['contact-id'].'>';
681 $mail['allow_gid'] = '';
682 $mail['deny_cid'] = '';
683 $mail['deny_gid'] = '';
684 $mail['private'] = true;
685 $mail['deleted'] = false;
686 $mail['edited'] = $mail['created'];
687 $mail['plink'] = $mail['uri'];
688 $mail['thr-parent'] = $reply['uri'];
689 $mail['gravity'] = ($mail['reply'] ? GRAVITY_COMMENT: GRAVITY_PARENT);
691 $mail['event-type'] = '';
692 $mail['attach'] = '';
700 * Creates an activity array for a given mail id
702 * @param integer $mail_id
703 * @param boolean $object_mode Is the activity item is used inside another object?
705 * @return array of activity
708 public static function createActivityFromMail($mail_id, $object_mode = false)
710 $mail = self::ItemArrayFromMail($mail_id);
711 $object = self::createNote($mail);
714 $data = ['@context' => ActivityPub::CONTEXT];
719 $data['id'] = $mail['uri'] . '#Create';
720 $data['type'] = 'Create';
721 $data['actor'] = $mail['author-link'];
722 $data['published'] = DateTimeFormat::utc($mail['created'] . '+00:00', DateTimeFormat::ATOM);
723 $data['instrument'] = self::getService();
724 $data = array_merge($data, self::createPermissionBlockForItem($mail, true));
726 if (empty($data['to']) && !empty($data['cc'])) {
727 $data['to'] = $data['cc'];
730 if (empty($data['to']) && !empty($data['bcc'])) {
731 $data['to'] = $data['bcc'];
737 $object['to'] = $data['to'];
738 $object['tag'] = [['type' => 'Mention', 'href' => $object['to'][0], 'name' => '']];
740 unset($object['cc']);
741 unset($object['bcc']);
743 $data['directMessage'] = true;
745 $data['object'] = $object;
747 $owner = User::getOwnerDataById($mail['uid']);
749 if (!$object_mode && !empty($owner)) {
750 return LDSignature::sign($data, $owner);
757 * Returns the activity type of a given item
761 * @return string with activity type
762 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
763 * @throws \ImagickException
765 private static function getTypeOfItem($item)
769 // Only check for a reshare, if it is a real reshare and no quoted reshare
770 if (strpos($item['body'], "[share") === 0) {
771 $announce = self::getAnnounceObject($item);
772 $reshared = !empty($announce);
777 } elseif ($item['verb'] == Activity::POST) {
778 if ($item['created'] == $item['edited']) {
783 } elseif ($item['verb'] == Activity::LIKE) {
785 } elseif ($item['verb'] == Activity::DISLIKE) {
787 } elseif ($item['verb'] == Activity::ATTEND) {
789 } elseif ($item['verb'] == Activity::ATTENDNO) {
791 } elseif ($item['verb'] == Activity::ATTENDMAYBE) {
792 $type = 'TentativeAccept';
793 } elseif ($item['verb'] == Activity::FOLLOW) {
795 } elseif ($item['verb'] == Activity::TAG) {
805 * Creates the activity or fetches it from the cache
807 * @param integer $item_id
808 * @param boolean $force Force new cache entry
810 * @return array with the activity
813 public static function createCachedActivityFromItem($item_id, $force = false)
815 $cachekey = 'APDelivery:createActivity:' . $item_id;
818 $data = Cache::get($cachekey);
819 if (!is_null($data)) {
824 $data = ActivityPub\Transmitter::createActivityFromItem($item_id);
826 Cache::set($cachekey, $data, Cache::QUARTER_HOUR);
831 * Creates an activity array for a given item id
833 * @param integer $item_id
834 * @param boolean $object_mode Is the activity item is used inside another object?
836 * @return array of activity
839 public static function createActivityFromItem($item_id, $object_mode = false)
841 $item = Item::selectFirst([], ['id' => $item_id, 'parent-network' => Protocol::NATIVE_SUPPORT]);
843 if (!DBA::isResult($item)) {
847 if ($item['wall'] && ($item['uri'] == $item['parent-uri'])) {
848 $owner = User::getOwnerDataById($item['uid']);
849 if (($owner['account-type'] == User::ACCOUNT_TYPE_COMMUNITY) && ($item['author-link'] != $owner['url'])) {
852 // Disguise forum posts as reshares. Will later be converted to a real announce
853 $item['body'] = share_header($item['author-name'], $item['author-link'], $item['author-avatar'],
854 $item['guid'], $item['created'], $item['plink']) . $item['body'] . '[/share]';
859 $condition = ['item-uri' => $item['uri'], 'protocol' => Conversation::PARCEL_ACTIVITYPUB];
860 $conversation = DBA::selectFirst('conversation', ['source'], $condition);
861 if (DBA::isResult($conversation)) {
862 $data = json_decode($conversation['source'], true);
868 $type = self::getTypeOfItem($item);
872 $data = ['@context' => ActivityPub::CONTEXT];
874 if ($item['deleted'] && ($item['gravity'] == GRAVITY_ACTIVITY)) {
876 } elseif ($item['deleted']) {
883 $data['id'] = $item['uri'] . '#' . $type;
884 $data['type'] = $type;
886 if (Item::isForumPost($item) && ($type != 'Announce')) {
887 $data['actor'] = $item['author-link'];
889 $data['actor'] = $item['owner-link'];
892 $data['published'] = DateTimeFormat::utc($item['created'] . '+00:00', DateTimeFormat::ATOM);
894 $data['instrument'] = self::getService();
896 $data = array_merge($data, self::createPermissionBlockForItem($item, false));
898 if (in_array($data['type'], ['Create', 'Update', 'Delete'])) {
899 $data['object'] = self::createNote($item);
900 } elseif ($data['type'] == 'Add') {
901 $data = self::createAddTag($item, $data);
902 } elseif ($data['type'] == 'Announce') {
903 $data = self::createAnnounce($item, $data);
904 } elseif ($data['type'] == 'Follow') {
905 $data['object'] = $item['parent-uri'];
906 } elseif ($data['type'] == 'Undo') {
907 $data['object'] = self::createActivityFromItem($item_id, true);
909 $data['diaspora:guid'] = $item['guid'];
910 if (!empty($item['signed_text'])) {
911 $data['diaspora:like'] = $item['signed_text'];
913 $data['object'] = $item['thr-parent'];
916 if (!empty($item['contact-uid'])) {
917 $uid = $item['contact-uid'];
922 $owner = User::getOwnerDataById($uid);
924 if (!$object_mode && !empty($owner)) {
925 return LDSignature::sign($data, $owner);
930 /// @todo Create "conversation" entry
934 * Creates a location entry for a given item array
938 * @return array with location array
940 private static function createLocation($item)
942 $location = ['type' => 'Place'];
944 if (!empty($item['location'])) {
945 $location['name'] = $item['location'];
950 if (empty($item['coord'])) {
951 $coord = Map::getCoordinates($item['location']);
953 $coords = explode(' ', $item['coord']);
954 if (count($coords) == 2) {
955 $coord = ['lat' => $coords[0], 'lon' => $coords[1]];
959 if (!empty($coord['lat']) && !empty($coord['lon'])) {
960 $location['latitude'] = $coord['lat'];
961 $location['longitude'] = $coord['lon'];
968 * Returns a tag array for a given item array
972 * @return array of tags
973 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
975 private static function createTagList($item)
979 $terms = Term::tagArrayFromItemId($item['id'], [Term::HASHTAG, Term::MENTION, Term::IMPLICIT_MENTION]);
980 foreach ($terms as $term) {
981 if ($term['type'] == Term::HASHTAG) {
982 $url = System::baseUrl() . '/search?tag=' . urlencode($term['term']);
983 $tags[] = ['type' => 'Hashtag', 'href' => $url, 'name' => '#' . $term['term']];
984 } elseif ($term['type'] == Term::MENTION || $term['type'] == Term::IMPLICIT_MENTION) {
985 $contact = Contact::getDetailsByURL($term['url']);
986 if (!empty($contact['addr'])) {
987 $mention = '@' . $contact['addr'];
989 $mention = '@' . $term['url'];
992 $tags[] = ['type' => 'Mention', 'href' => $term['url'], 'name' => $mention];
996 $announce = self::getAnnounceObject($item);
997 // Mention the original author upon commented reshares
998 if (!empty($announce['comment'])) {
999 $tags[] = ['type' => 'Mention', 'href' => $announce['actor']['url'], 'name' => '@' . $announce['actor']['addr']];
1006 * Adds attachment data to the JSON document
1008 * @param array $item Data of the item that is to be posted
1009 * @param string $type Object type
1011 * @return array with attachment data
1012 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1014 private static function createAttachmentList($item, $type)
1018 // Currently deactivated, since it creates side effects on Mastodon and Pleroma.
1019 // It will be reactivated, once this cleared.
1021 $attach_data = BBCode::getAttachmentData($item['body']);
1022 if (!empty($attach_data['url'])) {
1023 $attachment = ['type' => 'Page',
1024 'mediaType' => 'text/html',
1025 'url' => $attach_data['url']];
1027 if (!empty($attach_data['title'])) {
1028 $attachment['name'] = $attach_data['title'];
1031 if (!empty($attach_data['description'])) {
1032 $attachment['summary'] = $attach_data['description'];
1035 if (!empty($attach_data['image'])) {
1036 $imgdata = Images::getInfoFromURLCached($attach_data['image']);
1038 $attachment['icon'] = ['type' => 'Image',
1039 'mediaType' => $imgdata['mime'],
1040 'width' => $imgdata[0],
1041 'height' => $imgdata[1],
1042 'url' => $attach_data['image']];
1046 $attachments[] = $attachment;
1049 $arr = explode('[/attach],', $item['attach']);
1051 foreach ($arr as $r) {
1053 $cnt = preg_match('|\[attach\]href=\"(.*?)\" length=\"(.*?)\" type=\"(.*?)\" title=\"(.*?)\"|', $r, $matches);
1055 $attributes = ['type' => 'Document',
1056 'mediaType' => $matches[3],
1057 'url' => $matches[1],
1060 if (trim($matches[4]) != '') {
1061 $attributes['name'] = trim($matches[4]);
1064 $attachments[] = $attributes;
1069 if ($type != 'Note') {
1070 return $attachments;
1073 // Simplify image codes
1074 $body = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '[img]$3[/img]', $item['body']);
1076 // Grab all pictures without alternative descriptions and create attachments out of them
1077 if (preg_match_all("/\[img\]([^\[\]]*)\[\/img\]/Usi", $body, $pictures)) {
1078 foreach ($pictures[1] as $picture) {
1079 $imgdata = Images::getInfoFromURLCached($picture);
1081 $attachments[] = ['type' => 'Document',
1082 'mediaType' => $imgdata['mime'],
1089 // Grab all pictures with alternative description and create attachments out of them
1090 if (preg_match_all("/\[img=([^\[\]]*)\]([^\[\]]*)\[\/img\]/Usi", $body, $pictures, PREG_SET_ORDER)) {
1091 foreach ($pictures as $picture) {
1092 $imgdata = Images::getInfoFromURLCached($picture[1]);
1094 $attachments[] = ['type' => 'Document',
1095 'mediaType' => $imgdata['mime'],
1096 'url' => $picture[1],
1097 'name' => $picture[2]];
1102 return $attachments;
1106 * @brief Callback function to replace a Friendica style mention in a mention that is used on AP
1108 * @param array $match Matching values for the callback
1109 * @return string Replaced mention
1110 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1112 private static function mentionCallback($match)
1114 if (empty($match[1])) {
1118 $data = Contact::getDetailsByURL($match[1]);
1119 if (empty($data['nick'])) {
1123 return '@[url=' . $data['url'] . ']' . $data['nick'] . '[/url]';
1127 * Remove image elements since they are added as attachment
1129 * @param string $body
1131 * @return string with removed images
1133 private static function removePictures($body)
1135 // Simplify image codes
1136 $body = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '[img]$3[/img]', $body);
1137 $body = preg_replace("/\[img\=(.*?)\](.*?)\[\/img\]/ism", '[img]$1[/img]', $body);
1139 // Now remove local links
1140 $body = preg_replace_callback(
1141 '/\[url=([^\[\]]*)\]\[img\](.*)\[\/img\]\[\/url\]/Usi',
1143 // We remove the link when it is a link to a local photo page
1144 if (Photo::isLocalPage($match[1])) {
1147 // otherwise we just return the link
1148 return '[url]' . $match[1] . '[/url]';
1153 // Remove all pictures
1154 $body = preg_replace("/\[img\]([^\[\]]*)\[\/img\]/Usi", '', $body);
1160 * Fetches the "context" value for a givem item array from the "conversation" table
1162 * @param array $item
1164 * @return string with context url
1165 * @throws \Exception
1167 private static function fetchContextURLForItem($item)
1169 $conversation = DBA::selectFirst('conversation', ['conversation-href', 'conversation-uri'], ['item-uri' => $item['parent-uri']]);
1170 if (DBA::isResult($conversation) && !empty($conversation['conversation-href'])) {
1171 $context_uri = $conversation['conversation-href'];
1172 } elseif (DBA::isResult($conversation) && !empty($conversation['conversation-uri'])) {
1173 $context_uri = $conversation['conversation-uri'];
1175 $context_uri = $item['parent-uri'] . '#context';
1177 return $context_uri;
1181 * Returns if the post contains sensitive content ("nsfw")
1183 * @param integer $item_id
1186 * @throws \Exception
1188 private static function isSensitive($item_id)
1190 $condition = ['otype' => TERM_OBJ_POST, 'oid' => $item_id, 'type' => TERM_HASHTAG, 'term' => 'nsfw'];
1191 return DBA::exists('term', $condition);
1195 * Creates event data
1197 * @param array $item
1199 * @return array with the event data
1200 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1202 public static function createEvent($item)
1205 $event['name'] = $item['event-summary'];
1206 $event['content'] = BBCode::convert($item['event-desc'], false, 9);
1207 $event['startTime'] = DateTimeFormat::utc($item['event-start'] . '+00:00', DateTimeFormat::ATOM);
1209 if (!$item['event-nofinish']) {
1210 $event['endTime'] = DateTimeFormat::utc($item['event-finish'] . '+00:00', DateTimeFormat::ATOM);
1213 if (!empty($item['event-location'])) {
1214 $item['location'] = $item['event-location'];
1215 $event['location'] = self::createLocation($item);
1222 * Creates a note/article object array
1224 * @param array $item
1226 * @return array with the object data
1227 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1228 * @throws \ImagickException
1230 public static function createNote($item)
1236 if ($item['event-type'] == 'event') {
1238 } elseif (!empty($item['title'])) {
1244 if ($item['deleted']) {
1245 $type = 'Tombstone';
1249 $data['id'] = $item['uri'];
1250 $data['type'] = $type;
1252 if ($item['deleted']) {
1256 $data['summary'] = BBCode::toPlaintext(BBCode::getAbstract($item['body'], Protocol::ACTIVITYPUB));
1258 if ($item['uri'] != $item['thr-parent']) {
1259 $data['inReplyTo'] = $item['thr-parent'];
1261 $data['inReplyTo'] = null;
1264 $data['diaspora:guid'] = $item['guid'];
1265 $data['published'] = DateTimeFormat::utc($item['created'] . '+00:00', DateTimeFormat::ATOM);
1267 if ($item['created'] != $item['edited']) {
1268 $data['updated'] = DateTimeFormat::utc($item['edited'] . '+00:00', DateTimeFormat::ATOM);
1271 $data['url'] = $item['plink'];
1272 $data['attributedTo'] = $item['author-link'];
1273 $data['sensitive'] = self::isSensitive($item['id']);
1274 $data['context'] = self::fetchContextURLForItem($item);
1276 if (!empty($item['title'])) {
1277 $data['name'] = BBCode::toPlaintext($item['title'], false);
1280 $permission_block = self::createPermissionBlockForItem($item, false);
1282 $body = $item['body'];
1284 if (empty($item['uid']) || !Feature::isEnabled($item['uid'], 'explicit_mentions')) {
1285 $body = self::prependMentions($body, $permission_block);
1288 if ($type == 'Note') {
1289 $body = self::removePictures($body);
1290 } elseif (($type == 'Article') && empty($data['summary'])) {
1291 $data['summary'] = BBCode::toPlaintext(Plaintext::shorten(self::removePictures($body), 1000));
1294 if ($type == 'Event') {
1295 $data = array_merge($data, self::createEvent($item));
1297 $regexp = "/[@!]\[url\=([^\[\]]*)\].*?\[\/url\]/ism";
1298 $body = preg_replace_callback($regexp, ['self', 'mentionCallback'], $body);
1300 $data['content'] = BBCode::convert($body, false, 9);
1303 $regexp = "/[@!]\[url\=([^\[\]]*)\].*?\[\/url\]/ism";
1304 $richbody = preg_replace_callback($regexp, ['self', 'mentionCallback'], $item['body']);
1305 $richbody = BBCode::removeAttachment($richbody);
1307 $data['contentMap']['text/html'] = BBCode::convert($richbody, false);
1308 $data['contentMap']['text/markdown'] = BBCode::toMarkdown($item["body"]);
1310 $data['source'] = ['content' => $item['body'], 'mediaType' => "text/bbcode"];
1312 if (!empty($item['signed_text']) && ($item['uri'] != $item['thr-parent'])) {
1313 $data['diaspora:comment'] = $item['signed_text'];
1316 $data['attachment'] = self::createAttachmentList($item, $type);
1317 $data['tag'] = self::createTagList($item);
1319 if (empty($data['location']) && (!empty($item['coord']) || !empty($item['location']))) {
1320 $data['location'] = self::createLocation($item);
1323 if (!empty($item['app'])) {
1324 $data['generator'] = ['type' => 'Application', 'name' => $item['app']];
1327 $data = array_merge($data, $permission_block);
1333 * Creates an an "add tag" entry
1335 * @param array $item
1336 * @param array $data activity data
1338 * @return array with activity data for adding tags
1339 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1340 * @throws \ImagickException
1342 private static function createAddTag($item, $data)
1344 $object = XML::parseString($item['object'], false);
1345 $target = XML::parseString($item["target"], false);
1347 $data['diaspora:guid'] = $item['guid'];
1348 $data['actor'] = $item['author-link'];
1349 $data['target'] = (string)$target->id;
1350 $data['summary'] = BBCode::toPlaintext($item['body']);
1351 $data['object'] = ['id' => (string)$object->id, 'type' => 'tag', 'name' => (string)$object->title, 'content' => (string)$object->content];
1357 * Creates an announce object entry
1359 * @param array $item
1360 * @param array $data activity data
1362 * @return array with activity data
1363 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1364 * @throws \ImagickException
1366 private static function createAnnounce($item, $data)
1368 $orig_body = $item['body'];
1369 $announce = self::getAnnounceObject($item);
1370 if (empty($announce)) {
1371 $data['type'] = 'Create';
1372 $data['object'] = self::createNote($item);
1376 // Fetch the original id of the object
1377 $activity = ActivityPub::fetchContent($announce['id'], $item['uid']);
1378 if (!empty($activity)) {
1379 $ldactivity = JsonLD::compact($activity);
1380 $id = JsonLD::fetchElement($ldactivity, '@id');
1381 $type = str_replace('as:', '', JsonLD::fetchElement($ldactivity, '@type'));
1383 if (empty($announce['comment'])) {
1384 // Pure announce, without a quote
1385 $data['type'] = 'Announce';
1386 $data['object'] = $id;
1391 $data['type'] = 'Create';
1392 $item['body'] = $announce['comment'] . "\n" . $id;
1393 $data['object'] = self::createNote($item);
1395 /// @todo Finally descide how to implement this in AP. This is a possible way:
1396 $data['object']['attachment'][] = ['type' => $type, 'id' => $id];
1398 $data['object']['source']['content'] = $orig_body;
1403 $item['body'] = $orig_body;
1404 $data['type'] = 'Create';
1405 $data['object'] = self::createNote($item);
1410 * Return announce related data if the item is an annunce
1412 * @param array $item
1416 public static function getAnnounceObject($item)
1418 $announce = api_share_as_retweet($item);
1419 if (empty($announce['plink'])) {
1423 /// @ToDo Check if the announced item is an AP object
1425 $profile = APContact::getByURL($announce['author-link'], false);
1426 if (empty($profile)) {
1430 return ['id' => $announce['plink'], 'actor' => $profile, 'comment' => trim($announce['share-pre-body'])];
1434 * Creates an activity id for a given contact id
1436 * @param integer $cid Contact ID of target
1438 * @return bool|string activity id
1440 public static function activityIDFromContact($cid)
1442 $contact = DBA::selectFirst('contact', ['uid', 'id', 'created'], ['id' => $cid]);
1443 if (!DBA::isResult($contact)) {
1447 $hash = hash('ripemd128', $contact['uid'].'-'.$contact['id'].'-'.$contact['created']);
1448 $uuid = substr($hash, 0, 8). '-' . substr($hash, 8, 4) . '-' . substr($hash, 12, 4) . '-' . substr($hash, 16, 4) . '-' . substr($hash, 20, 12);
1449 return System::baseUrl() . '/activity/' . $uuid;
1453 * Transmits a contact suggestion to a given inbox
1455 * @param integer $uid User ID
1456 * @param string $inbox Target inbox
1457 * @param integer $suggestion_id Suggestion ID
1459 * @return boolean was the transmission successful?
1460 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1462 public static function sendContactSuggestion($uid, $inbox, $suggestion_id)
1464 $owner = User::getOwnerDataById($uid);
1466 $suggestion = DBA::selectFirst('fsuggest', ['url', 'note', 'created'], ['id' => $suggestion_id]);
1468 $data = ['@context' => ActivityPub::CONTEXT,
1469 'id' => System::baseUrl() . '/activity/' . System::createGUID(),
1470 'type' => 'Announce',
1471 'actor' => $owner['url'],
1472 'object' => $suggestion['url'],
1473 'content' => $suggestion['note'],
1474 'instrument' => self::getService(),
1475 'to' => [ActivityPub::PUBLIC_COLLECTION],
1478 $signed = LDSignature::sign($data, $owner);
1480 Logger::log('Deliver profile deletion for user ' . $uid . ' to ' . $inbox . ' via ActivityPub', Logger::DEBUG);
1481 return HTTPSignature::transmit($signed, $inbox, $uid);
1485 * Transmits a profile relocation to a given inbox
1487 * @param integer $uid User ID
1488 * @param string $inbox Target inbox
1490 * @return boolean was the transmission successful?
1491 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1493 public static function sendProfileRelocation($uid, $inbox)
1495 $owner = User::getOwnerDataById($uid);
1497 $data = ['@context' => ActivityPub::CONTEXT,
1498 'id' => System::baseUrl() . '/activity/' . System::createGUID(),
1499 'type' => 'dfrn:relocate',
1500 'actor' => $owner['url'],
1501 'object' => $owner['url'],
1502 'published' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
1503 'instrument' => self::getService(),
1504 'to' => [ActivityPub::PUBLIC_COLLECTION],
1507 $signed = LDSignature::sign($data, $owner);
1509 Logger::log('Deliver profile relocation for user ' . $uid . ' to ' . $inbox . ' via ActivityPub', Logger::DEBUG);
1510 return HTTPSignature::transmit($signed, $inbox, $uid);
1514 * Transmits a profile deletion to a given inbox
1516 * @param integer $uid User ID
1517 * @param string $inbox Target inbox
1519 * @return boolean was the transmission successful?
1520 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1522 public static function sendProfileDeletion($uid, $inbox)
1524 $owner = User::getOwnerDataById($uid);
1526 if (empty($owner)) {
1527 Logger::error('No owner data found, the deletion message cannot be processed.', ['user' => $uid]);
1531 if (empty($owner['uprvkey'])) {
1532 Logger::error('No private key for owner found, the deletion message cannot be processed.', ['user' => $uid]);
1536 $data = ['@context' => ActivityPub::CONTEXT,
1537 'id' => System::baseUrl() . '/activity/' . System::createGUID(),
1539 'actor' => $owner['url'],
1540 'object' => $owner['url'],
1541 'published' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
1542 'instrument' => self::getService(),
1543 'to' => [ActivityPub::PUBLIC_COLLECTION],
1546 $signed = LDSignature::sign($data, $owner);
1548 Logger::log('Deliver profile deletion for user ' . $uid . ' to ' . $inbox . ' via ActivityPub', Logger::DEBUG);
1549 return HTTPSignature::transmit($signed, $inbox, $uid);
1553 * Transmits a profile change to a given inbox
1555 * @param integer $uid User ID
1556 * @param string $inbox Target inbox
1558 * @return boolean was the transmission successful?
1559 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1560 * @throws \ImagickException
1562 public static function sendProfileUpdate($uid, $inbox)
1564 $owner = User::getOwnerDataById($uid);
1565 $profile = APContact::getByURL($owner['url']);
1567 $data = ['@context' => ActivityPub::CONTEXT,
1568 'id' => System::baseUrl() . '/activity/' . System::createGUID(),
1570 'actor' => $owner['url'],
1571 'object' => self::getProfile($uid),
1572 'published' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
1573 'instrument' => self::getService(),
1574 'to' => [$profile['followers']],
1577 $signed = LDSignature::sign($data, $owner);
1579 Logger::log('Deliver profile update for user ' . $uid . ' to ' . $inbox . ' via ActivityPub', Logger::DEBUG);
1580 return HTTPSignature::transmit($signed, $inbox, $uid);
1584 * Transmits a given activity to a target
1586 * @param string $activity Type name
1587 * @param string $target Target profile
1588 * @param integer $uid User ID
1590 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1591 * @throws \ImagickException
1592 * @throws \Exception
1594 public static function sendActivity($activity, $target, $uid, $id = '')
1596 $profile = APContact::getByURL($target);
1597 if (empty($profile['inbox'])) {
1598 Logger::warning('No inbox found for target', ['target' => $target, 'profile' => $profile]);
1602 $owner = User::getOwnerDataById($uid);
1605 $id = System::baseUrl() . '/activity/' . System::createGUID();
1608 $data = ['@context' => ActivityPub::CONTEXT,
1610 'type' => $activity,
1611 'actor' => $owner['url'],
1612 'object' => $profile['url'],
1613 'instrument' => self::getService(),
1614 'to' => [$profile['url']]];
1616 Logger::log('Sending activity ' . $activity . ' to ' . $target . ' for user ' . $uid, Logger::DEBUG);
1618 $signed = LDSignature::sign($data, $owner);
1619 return HTTPSignature::transmit($signed, $profile['inbox'], $uid);
1623 * Transmits a "follow object" activity to a target
1624 * This is a preparation for sending automated "follow" requests when receiving "Announce" messages
1626 * @param string $object Object URL
1627 * @param string $target Target profile
1628 * @param integer $uid User ID
1630 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1631 * @throws \ImagickException
1632 * @throws \Exception
1634 public static function sendFollowObject($object, $target, $uid = 0)
1636 $profile = APContact::getByURL($target);
1637 if (empty($profile['inbox'])) {
1638 Logger::warning('No inbox found for target', ['target' => $target, 'profile' => $profile]);
1643 // Fetch the list of administrators
1644 $admin_mail = explode(',', str_replace(' ', '', Config::get('config', 'admin_email')));
1646 // We need to use some user as a sender. It doesn't care who it will send. We will use an administrator account.
1647 $condition = ['verified' => true, 'blocked' => false, 'account_removed' => false, 'account_expired' => false, 'email' => $admin_mail];
1648 $first_user = DBA::selectFirst('user', ['uid'], $condition);
1649 $uid = $first_user['uid'];
1652 $condition = ['verb' => Activity::FOLLOW, 'uid' => 0, 'parent-uri' => $object,
1653 'author-id' => Contact::getPublicIdByUserId($uid)];
1654 if (Item::exists($condition)) {
1655 Logger::log('Follow for ' . $object . ' for user ' . $uid . ' does already exist.', Logger::DEBUG);
1659 $owner = User::getOwnerDataById($uid);
1661 $data = ['@context' => ActivityPub::CONTEXT,
1662 'id' => System::baseUrl() . '/activity/' . System::createGUID(),
1664 'actor' => $owner['url'],
1665 'object' => $object,
1666 'instrument' => self::getService(),
1667 'to' => [$profile['url']]];
1669 Logger::log('Sending follow ' . $object . ' to ' . $target . ' for user ' . $uid, Logger::DEBUG);
1671 $signed = LDSignature::sign($data, $owner);
1672 return HTTPSignature::transmit($signed, $profile['inbox'], $uid);
1676 * Transmit a message that the contact request had been accepted
1678 * @param string $target Target profile
1680 * @param integer $uid User ID
1681 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1682 * @throws \ImagickException
1684 public static function sendContactAccept($target, $id, $uid)
1686 $profile = APContact::getByURL($target);
1687 if (empty($profile['inbox'])) {
1688 Logger::warning('No inbox found for target', ['target' => $target, 'profile' => $profile]);
1692 $owner = User::getOwnerDataById($uid);
1693 $data = ['@context' => ActivityPub::CONTEXT,
1694 'id' => System::baseUrl() . '/activity/' . System::createGUID(),
1696 'actor' => $owner['url'],
1698 'id' => (string)$id,
1700 'actor' => $profile['url'],
1701 'object' => $owner['url']
1703 'instrument' => self::getService(),
1704 'to' => [$profile['url']]];
1706 Logger::debug('Sending accept to ' . $target . ' for user ' . $uid . ' with id ' . $id);
1708 $signed = LDSignature::sign($data, $owner);
1709 HTTPSignature::transmit($signed, $profile['inbox'], $uid);
1713 * Reject a contact request or terminates the contact relation
1715 * @param string $target Target profile
1717 * @param integer $uid User ID
1718 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1719 * @throws \ImagickException
1721 public static function sendContactReject($target, $id, $uid)
1723 $profile = APContact::getByURL($target);
1724 if (empty($profile['inbox'])) {
1725 Logger::warning('No inbox found for target', ['target' => $target, 'profile' => $profile]);
1729 $owner = User::getOwnerDataById($uid);
1730 $data = ['@context' => ActivityPub::CONTEXT,
1731 'id' => System::baseUrl() . '/activity/' . System::createGUID(),
1733 'actor' => $owner['url'],
1735 'id' => (string)$id,
1737 'actor' => $profile['url'],
1738 'object' => $owner['url']
1740 'instrument' => self::getService(),
1741 'to' => [$profile['url']]];
1743 Logger::debug('Sending reject to ' . $target . ' for user ' . $uid . ' with id ' . $id);
1745 $signed = LDSignature::sign($data, $owner);
1746 HTTPSignature::transmit($signed, $profile['inbox'], $uid);
1750 * Transmits a message that we don't want to follow this contact anymore
1752 * @param string $target Target profile
1753 * @param integer $uid User ID
1754 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1755 * @throws \ImagickException
1756 * @throws \Exception
1758 public static function sendContactUndo($target, $cid, $uid)
1760 $profile = APContact::getByURL($target);
1761 if (empty($profile['inbox'])) {
1762 Logger::warning('No inbox found for target', ['target' => $target, 'profile' => $profile]);
1766 $object_id = self::activityIDFromContact($cid);
1767 if (empty($object_id)) {
1771 $id = System::baseUrl() . '/activity/' . System::createGUID();
1773 $owner = User::getOwnerDataById($uid);
1774 $data = ['@context' => ActivityPub::CONTEXT,
1777 'actor' => $owner['url'],
1778 'object' => ['id' => $object_id, 'type' => 'Follow',
1779 'actor' => $owner['url'],
1780 'object' => $profile['url']],
1781 'instrument' => self::getService(),
1782 'to' => [$profile['url']]];
1784 Logger::log('Sending undo to ' . $target . ' for user ' . $uid . ' with id ' . $id, Logger::DEBUG);
1786 $signed = LDSignature::sign($data, $owner);
1787 HTTPSignature::transmit($signed, $profile['inbox'], $uid);
1790 private static function prependMentions($body, array $permission_block)
1792 if (Config::get('system', 'disable_implicit_mentions')) {
1798 foreach ($permission_block['to'] as $profile_url) {
1799 $profile = Contact::getDetailsByURL($profile_url);
1800 if (!empty($profile['addr'])
1801 && $profile['contact-type'] != Contact::TYPE_COMMUNITY
1802 && !strstr($body, $profile['addr'])
1803 && !strstr($body, $profile_url)
1805 $mentions[] = '@[url=' . $profile_url . ']' . $profile['nick'] . '[/url]';
1809 $mentions[] = $body;
1811 return implode(' ', $mentions);