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 an object array for a given item id
936 * @param integer $item_id
938 * @return array with the object data
939 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
940 * @throws \ImagickException
942 public static function createObjectFromItemID($item_id)
944 $item = Item::selectFirst([], ['id' => $item_id, 'parent-network' => Protocol::NATIVE_SUPPORT]);
946 if (!DBA::isResult($item)) {
950 $data = ['@context' => ActivityPub::CONTEXT];
951 $data = array_merge($data, self::createNote($item));
957 * Creates a location entry for a given item array
961 * @return array with location array
963 private static function createLocation($item)
965 $location = ['type' => 'Place'];
967 if (!empty($item['location'])) {
968 $location['name'] = $item['location'];
973 if (empty($item['coord'])) {
974 $coord = Map::getCoordinates($item['location']);
976 $coords = explode(' ', $item['coord']);
977 if (count($coords) == 2) {
978 $coord = ['lat' => $coords[0], 'lon' => $coords[1]];
982 if (!empty($coord['lat']) && !empty($coord['lon'])) {
983 $location['latitude'] = $coord['lat'];
984 $location['longitude'] = $coord['lon'];
991 * Returns a tag array for a given item array
995 * @return array of tags
996 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
998 private static function createTagList($item)
1002 $terms = Term::tagArrayFromItemId($item['id'], [Term::HASHTAG, Term::MENTION, Term::IMPLICIT_MENTION]);
1003 foreach ($terms as $term) {
1004 if ($term['type'] == Term::HASHTAG) {
1005 $url = System::baseUrl() . '/search?tag=' . urlencode($term['term']);
1006 $tags[] = ['type' => 'Hashtag', 'href' => $url, 'name' => '#' . $term['term']];
1007 } elseif ($term['type'] == Term::MENTION || $term['type'] == Term::IMPLICIT_MENTION) {
1008 $contact = Contact::getDetailsByURL($term['url']);
1009 if (!empty($contact['addr'])) {
1010 $mention = '@' . $contact['addr'];
1012 $mention = '@' . $term['url'];
1015 $tags[] = ['type' => 'Mention', 'href' => $term['url'], 'name' => $mention];
1019 $announce = self::getAnnounceObject($item);
1020 // Mention the original author upon commented reshares
1021 if (!empty($announce['comment'])) {
1022 $tags[] = ['type' => 'Mention', 'href' => $announce['actor']['url'], 'name' => '@' . $announce['actor']['addr']];
1029 * Adds attachment data to the JSON document
1031 * @param array $item Data of the item that is to be posted
1032 * @param string $type Object type
1034 * @return array with attachment data
1035 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1037 private static function createAttachmentList($item, $type)
1041 // Currently deactivated, since it creates side effects on Mastodon and Pleroma.
1042 // It will be reactivated, once this cleared.
1044 $attach_data = BBCode::getAttachmentData($item['body']);
1045 if (!empty($attach_data['url'])) {
1046 $attachment = ['type' => 'Page',
1047 'mediaType' => 'text/html',
1048 'url' => $attach_data['url']];
1050 if (!empty($attach_data['title'])) {
1051 $attachment['name'] = $attach_data['title'];
1054 if (!empty($attach_data['description'])) {
1055 $attachment['summary'] = $attach_data['description'];
1058 if (!empty($attach_data['image'])) {
1059 $imgdata = Images::getInfoFromURLCached($attach_data['image']);
1061 $attachment['icon'] = ['type' => 'Image',
1062 'mediaType' => $imgdata['mime'],
1063 'width' => $imgdata[0],
1064 'height' => $imgdata[1],
1065 'url' => $attach_data['image']];
1069 $attachments[] = $attachment;
1072 $arr = explode('[/attach],', $item['attach']);
1074 foreach ($arr as $r) {
1076 $cnt = preg_match('|\[attach\]href=\"(.*?)\" length=\"(.*?)\" type=\"(.*?)\" title=\"(.*?)\"|', $r, $matches);
1078 $attributes = ['type' => 'Document',
1079 'mediaType' => $matches[3],
1080 'url' => $matches[1],
1083 if (trim($matches[4]) != '') {
1084 $attributes['name'] = trim($matches[4]);
1087 $attachments[] = $attributes;
1092 if ($type != 'Note') {
1093 return $attachments;
1096 // Simplify image codes
1097 $body = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '[img]$3[/img]', $item['body']);
1099 // Grab all pictures without alternative descriptions and create attachments out of them
1100 if (preg_match_all("/\[img\]([^\[\]]*)\[\/img\]/Usi", $body, $pictures)) {
1101 foreach ($pictures[1] as $picture) {
1102 $imgdata = Images::getInfoFromURLCached($picture);
1104 $attachments[] = ['type' => 'Document',
1105 'mediaType' => $imgdata['mime'],
1112 // Grab all pictures with alternative description and create attachments out of them
1113 if (preg_match_all("/\[img=([^\[\]]*)\]([^\[\]]*)\[\/img\]/Usi", $body, $pictures, PREG_SET_ORDER)) {
1114 foreach ($pictures as $picture) {
1115 $imgdata = Images::getInfoFromURLCached($picture[1]);
1117 $attachments[] = ['type' => 'Document',
1118 'mediaType' => $imgdata['mime'],
1119 'url' => $picture[1],
1120 'name' => $picture[2]];
1125 return $attachments;
1129 * @brief Callback function to replace a Friendica style mention in a mention that is used on AP
1131 * @param array $match Matching values for the callback
1132 * @return string Replaced mention
1133 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1135 private static function mentionCallback($match)
1137 if (empty($match[1])) {
1141 $data = Contact::getDetailsByURL($match[1]);
1142 if (empty($data['nick'])) {
1146 return '@[url=' . $data['url'] . ']' . $data['nick'] . '[/url]';
1150 * Remove image elements since they are added as attachment
1152 * @param string $body
1154 * @return string with removed images
1156 private static function removePictures($body)
1158 // Simplify image codes
1159 $body = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '[img]$3[/img]', $body);
1160 $body = preg_replace("/\[img\=(.*?)\](.*?)\[\/img\]/ism", '[img]$1[/img]', $body);
1162 // Now remove local links
1163 $body = preg_replace_callback(
1164 '/\[url=([^\[\]]*)\]\[img\](.*)\[\/img\]\[\/url\]/Usi',
1166 // We remove the link when it is a link to a local photo page
1167 if (Photo::isLocalPage($match[1])) {
1170 // otherwise we just return the link
1171 return '[url]' . $match[1] . '[/url]';
1176 // Remove all pictures
1177 $body = preg_replace("/\[img\]([^\[\]]*)\[\/img\]/Usi", '', $body);
1183 * Fetches the "context" value for a givem item array from the "conversation" table
1185 * @param array $item
1187 * @return string with context url
1188 * @throws \Exception
1190 private static function fetchContextURLForItem($item)
1192 $conversation = DBA::selectFirst('conversation', ['conversation-href', 'conversation-uri'], ['item-uri' => $item['parent-uri']]);
1193 if (DBA::isResult($conversation) && !empty($conversation['conversation-href'])) {
1194 $context_uri = $conversation['conversation-href'];
1195 } elseif (DBA::isResult($conversation) && !empty($conversation['conversation-uri'])) {
1196 $context_uri = $conversation['conversation-uri'];
1198 $context_uri = $item['parent-uri'] . '#context';
1200 return $context_uri;
1204 * Returns if the post contains sensitive content ("nsfw")
1206 * @param integer $item_id
1209 * @throws \Exception
1211 private static function isSensitive($item_id)
1213 $condition = ['otype' => TERM_OBJ_POST, 'oid' => $item_id, 'type' => TERM_HASHTAG, 'term' => 'nsfw'];
1214 return DBA::exists('term', $condition);
1218 * Creates event data
1220 * @param array $item
1222 * @return array with the event data
1223 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1225 public static function createEvent($item)
1228 $event['name'] = $item['event-summary'];
1229 $event['content'] = BBCode::convert($item['event-desc'], false, 9);
1230 $event['startTime'] = DateTimeFormat::utc($item['event-start'] . '+00:00', DateTimeFormat::ATOM);
1232 if (!$item['event-nofinish']) {
1233 $event['endTime'] = DateTimeFormat::utc($item['event-finish'] . '+00:00', DateTimeFormat::ATOM);
1236 if (!empty($item['event-location'])) {
1237 $item['location'] = $item['event-location'];
1238 $event['location'] = self::createLocation($item);
1245 * Creates a note/article object array
1247 * @param array $item
1249 * @return array with the object data
1250 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1251 * @throws \ImagickException
1253 public static function createNote($item)
1259 if ($item['event-type'] == 'event') {
1261 } elseif (!empty($item['title'])) {
1267 if ($item['deleted']) {
1268 $type = 'Tombstone';
1272 $data['id'] = $item['uri'];
1273 $data['type'] = $type;
1275 if ($item['deleted']) {
1279 $data['summary'] = BBCode::toPlaintext(BBCode::getAbstract($item['body'], Protocol::ACTIVITYPUB));
1281 if ($item['uri'] != $item['thr-parent']) {
1282 $data['inReplyTo'] = $item['thr-parent'];
1284 $data['inReplyTo'] = null;
1287 $data['diaspora:guid'] = $item['guid'];
1288 $data['published'] = DateTimeFormat::utc($item['created'] . '+00:00', DateTimeFormat::ATOM);
1290 if ($item['created'] != $item['edited']) {
1291 $data['updated'] = DateTimeFormat::utc($item['edited'] . '+00:00', DateTimeFormat::ATOM);
1294 $data['url'] = $item['plink'];
1295 $data['attributedTo'] = $item['author-link'];
1296 $data['sensitive'] = self::isSensitive($item['id']);
1297 $data['context'] = self::fetchContextURLForItem($item);
1299 if (!empty($item['title'])) {
1300 $data['name'] = BBCode::toPlaintext($item['title'], false);
1303 $permission_block = self::createPermissionBlockForItem($item, false);
1305 $body = $item['body'];
1307 if (empty($item['uid']) || !Feature::isEnabled($item['uid'], 'explicit_mentions')) {
1308 $body = self::prependMentions($body, $permission_block);
1311 if ($type == 'Note') {
1312 $body = self::removePictures($body);
1313 } elseif (($type == 'Article') && empty($data['summary'])) {
1314 $data['summary'] = BBCode::toPlaintext(Plaintext::shorten(self::removePictures($body), 1000));
1317 if ($type == 'Event') {
1318 $data = array_merge($data, self::createEvent($item));
1320 $regexp = "/[@!]\[url\=([^\[\]]*)\].*?\[\/url\]/ism";
1321 $body = preg_replace_callback($regexp, ['self', 'mentionCallback'], $body);
1323 $data['content'] = BBCode::convert($body, false, 9);
1326 $regexp = "/[@!]\[url\=([^\[\]]*)\].*?\[\/url\]/ism";
1327 $richbody = preg_replace_callback($regexp, ['self', 'mentionCallback'], $item['body']);
1328 $richbody = BBCode::removeAttachment($richbody);
1330 $data['contentMap']['text/html'] = BBCode::convert($richbody, false);
1331 $data['contentMap']['text/markdown'] = BBCode::toMarkdown($item["body"]);
1333 $data['source'] = ['content' => $item['body'], 'mediaType' => "text/bbcode"];
1335 if (!empty($item['signed_text']) && ($item['uri'] != $item['thr-parent'])) {
1336 $data['diaspora:comment'] = $item['signed_text'];
1339 $data['attachment'] = self::createAttachmentList($item, $type);
1340 $data['tag'] = self::createTagList($item);
1342 if (empty($data['location']) && (!empty($item['coord']) || !empty($item['location']))) {
1343 $data['location'] = self::createLocation($item);
1346 if (!empty($item['app'])) {
1347 $data['generator'] = ['type' => 'Application', 'name' => $item['app']];
1350 $data = array_merge($data, $permission_block);
1356 * Creates an an "add tag" entry
1358 * @param array $item
1359 * @param array $data activity data
1361 * @return array with activity data for adding tags
1362 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1363 * @throws \ImagickException
1365 private static function createAddTag($item, $data)
1367 $object = XML::parseString($item['object'], false);
1368 $target = XML::parseString($item["target"], false);
1370 $data['diaspora:guid'] = $item['guid'];
1371 $data['actor'] = $item['author-link'];
1372 $data['target'] = (string)$target->id;
1373 $data['summary'] = BBCode::toPlaintext($item['body']);
1374 $data['object'] = ['id' => (string)$object->id, 'type' => 'tag', 'name' => (string)$object->title, 'content' => (string)$object->content];
1380 * Creates an announce object entry
1382 * @param array $item
1383 * @param array $data activity data
1385 * @return array with activity data
1386 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1387 * @throws \ImagickException
1389 private static function createAnnounce($item, $data)
1391 $orig_body = $item['body'];
1392 $announce = self::getAnnounceObject($item);
1393 if (empty($announce)) {
1394 $data['type'] = 'Create';
1395 $data['object'] = self::createNote($item);
1399 // Fetch the original id of the object
1400 $activity = ActivityPub::fetchContent($announce['id'], $item['uid']);
1401 if (!empty($activity)) {
1402 $ldactivity = JsonLD::compact($activity);
1403 $id = JsonLD::fetchElement($ldactivity, '@id');
1404 $type = str_replace('as:', '', JsonLD::fetchElement($ldactivity, '@type'));
1406 if (empty($announce['comment'])) {
1407 // Pure announce, without a quote
1408 $data['type'] = 'Announce';
1409 $data['object'] = $id;
1414 $data['type'] = 'Create';
1415 $item['body'] = $announce['comment'] . "\n" . $id;
1416 $data['object'] = self::createNote($item);
1418 /// @todo Finally descide how to implement this in AP. This is a possible way:
1419 $data['object']['attachment'][] = ['type' => $type, 'id' => $id];
1421 $data['object']['source']['content'] = $orig_body;
1426 $item['body'] = $orig_body;
1427 $data['type'] = 'Create';
1428 $data['object'] = self::createNote($item);
1433 * Return announce related data if the item is an annunce
1435 * @param array $item
1439 public static function getAnnounceObject($item)
1441 $announce = api_share_as_retweet($item);
1442 if (empty($announce['plink'])) {
1446 /// @ToDo Check if the announced item is an AP object
1448 $profile = APContact::getByURL($announce['author-link'], false);
1449 if (empty($profile)) {
1453 return ['id' => $announce['plink'], 'actor' => $profile, 'comment' => trim($announce['share-pre-body'])];
1457 * Creates an activity id for a given contact id
1459 * @param integer $cid Contact ID of target
1461 * @return bool|string activity id
1463 public static function activityIDFromContact($cid)
1465 $contact = DBA::selectFirst('contact', ['uid', 'id', 'created'], ['id' => $cid]);
1466 if (!DBA::isResult($contact)) {
1470 $hash = hash('ripemd128', $contact['uid'].'-'.$contact['id'].'-'.$contact['created']);
1471 $uuid = substr($hash, 0, 8). '-' . substr($hash, 8, 4) . '-' . substr($hash, 12, 4) . '-' . substr($hash, 16, 4) . '-' . substr($hash, 20, 12);
1472 return System::baseUrl() . '/activity/' . $uuid;
1476 * Transmits a contact suggestion to a given inbox
1478 * @param integer $uid User ID
1479 * @param string $inbox Target inbox
1480 * @param integer $suggestion_id Suggestion ID
1482 * @return boolean was the transmission successful?
1483 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1485 public static function sendContactSuggestion($uid, $inbox, $suggestion_id)
1487 $owner = User::getOwnerDataById($uid);
1489 $suggestion = DBA::selectFirst('fsuggest', ['url', 'note', 'created'], ['id' => $suggestion_id]);
1491 $data = ['@context' => ActivityPub::CONTEXT,
1492 'id' => System::baseUrl() . '/activity/' . System::createGUID(),
1493 'type' => 'Announce',
1494 'actor' => $owner['url'],
1495 'object' => $suggestion['url'],
1496 'content' => $suggestion['note'],
1497 'instrument' => self::getService(),
1498 'to' => [ActivityPub::PUBLIC_COLLECTION],
1501 $signed = LDSignature::sign($data, $owner);
1503 Logger::log('Deliver profile deletion for user ' . $uid . ' to ' . $inbox . ' via ActivityPub', Logger::DEBUG);
1504 return HTTPSignature::transmit($signed, $inbox, $uid);
1508 * Transmits a profile relocation to a given inbox
1510 * @param integer $uid User ID
1511 * @param string $inbox Target inbox
1513 * @return boolean was the transmission successful?
1514 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1516 public static function sendProfileRelocation($uid, $inbox)
1518 $owner = User::getOwnerDataById($uid);
1520 $data = ['@context' => ActivityPub::CONTEXT,
1521 'id' => System::baseUrl() . '/activity/' . System::createGUID(),
1522 'type' => 'dfrn:relocate',
1523 'actor' => $owner['url'],
1524 'object' => $owner['url'],
1525 'published' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
1526 'instrument' => self::getService(),
1527 'to' => [ActivityPub::PUBLIC_COLLECTION],
1530 $signed = LDSignature::sign($data, $owner);
1532 Logger::log('Deliver profile relocation for user ' . $uid . ' to ' . $inbox . ' via ActivityPub', Logger::DEBUG);
1533 return HTTPSignature::transmit($signed, $inbox, $uid);
1537 * Transmits a profile deletion to a given inbox
1539 * @param integer $uid User ID
1540 * @param string $inbox Target inbox
1542 * @return boolean was the transmission successful?
1543 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1545 public static function sendProfileDeletion($uid, $inbox)
1547 $owner = User::getOwnerDataById($uid);
1549 if (empty($owner)) {
1550 Logger::error('No owner data found, the deletion message cannot be processed.', ['user' => $uid]);
1554 if (empty($owner['uprvkey'])) {
1555 Logger::error('No private key for owner found, the deletion message cannot be processed.', ['user' => $uid]);
1559 $data = ['@context' => ActivityPub::CONTEXT,
1560 'id' => System::baseUrl() . '/activity/' . System::createGUID(),
1562 'actor' => $owner['url'],
1563 'object' => $owner['url'],
1564 'published' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
1565 'instrument' => self::getService(),
1566 'to' => [ActivityPub::PUBLIC_COLLECTION],
1569 $signed = LDSignature::sign($data, $owner);
1571 Logger::log('Deliver profile deletion for user ' . $uid . ' to ' . $inbox . ' via ActivityPub', Logger::DEBUG);
1572 return HTTPSignature::transmit($signed, $inbox, $uid);
1576 * Transmits a profile change to a given inbox
1578 * @param integer $uid User ID
1579 * @param string $inbox Target inbox
1581 * @return boolean was the transmission successful?
1582 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1583 * @throws \ImagickException
1585 public static function sendProfileUpdate($uid, $inbox)
1587 $owner = User::getOwnerDataById($uid);
1588 $profile = APContact::getByURL($owner['url']);
1590 $data = ['@context' => ActivityPub::CONTEXT,
1591 'id' => System::baseUrl() . '/activity/' . System::createGUID(),
1593 'actor' => $owner['url'],
1594 'object' => self::getProfile($uid),
1595 'published' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
1596 'instrument' => self::getService(),
1597 'to' => [$profile['followers']],
1600 $signed = LDSignature::sign($data, $owner);
1602 Logger::log('Deliver profile update for user ' . $uid . ' to ' . $inbox . ' via ActivityPub', Logger::DEBUG);
1603 return HTTPSignature::transmit($signed, $inbox, $uid);
1607 * Transmits a given activity to a target
1609 * @param string $activity Type name
1610 * @param string $target Target profile
1611 * @param integer $uid User ID
1613 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1614 * @throws \ImagickException
1615 * @throws \Exception
1617 public static function sendActivity($activity, $target, $uid, $id = '')
1619 $profile = APContact::getByURL($target);
1620 if (empty($profile['inbox'])) {
1621 Logger::warning('No inbox found for target', ['target' => $target, 'profile' => $profile]);
1625 $owner = User::getOwnerDataById($uid);
1628 $id = System::baseUrl() . '/activity/' . System::createGUID();
1631 $data = ['@context' => ActivityPub::CONTEXT,
1633 'type' => $activity,
1634 'actor' => $owner['url'],
1635 'object' => $profile['url'],
1636 'instrument' => self::getService(),
1637 'to' => [$profile['url']]];
1639 Logger::log('Sending activity ' . $activity . ' to ' . $target . ' for user ' . $uid, Logger::DEBUG);
1641 $signed = LDSignature::sign($data, $owner);
1642 return HTTPSignature::transmit($signed, $profile['inbox'], $uid);
1646 * Transmits a "follow object" activity to a target
1647 * This is a preparation for sending automated "follow" requests when receiving "Announce" messages
1649 * @param string $object Object URL
1650 * @param string $target Target profile
1651 * @param integer $uid User ID
1653 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1654 * @throws \ImagickException
1655 * @throws \Exception
1657 public static function sendFollowObject($object, $target, $uid = 0)
1659 $profile = APContact::getByURL($target);
1660 if (empty($profile['inbox'])) {
1661 Logger::warning('No inbox found for target', ['target' => $target, 'profile' => $profile]);
1666 // Fetch the list of administrators
1667 $admin_mail = explode(',', str_replace(' ', '', Config::get('config', 'admin_email')));
1669 // We need to use some user as a sender. It doesn't care who it will send. We will use an administrator account.
1670 $condition = ['verified' => true, 'blocked' => false, 'account_removed' => false, 'account_expired' => false, 'email' => $admin_mail];
1671 $first_user = DBA::selectFirst('user', ['uid'], $condition);
1672 $uid = $first_user['uid'];
1675 $condition = ['verb' => Activity::FOLLOW, 'uid' => 0, 'parent-uri' => $object,
1676 'author-id' => Contact::getPublicIdByUserId($uid)];
1677 if (Item::exists($condition)) {
1678 Logger::log('Follow for ' . $object . ' for user ' . $uid . ' does already exist.', Logger::DEBUG);
1682 $owner = User::getOwnerDataById($uid);
1684 $data = ['@context' => ActivityPub::CONTEXT,
1685 'id' => System::baseUrl() . '/activity/' . System::createGUID(),
1687 'actor' => $owner['url'],
1688 'object' => $object,
1689 'instrument' => self::getService(),
1690 'to' => [$profile['url']]];
1692 Logger::log('Sending follow ' . $object . ' to ' . $target . ' for user ' . $uid, Logger::DEBUG);
1694 $signed = LDSignature::sign($data, $owner);
1695 return HTTPSignature::transmit($signed, $profile['inbox'], $uid);
1699 * Transmit a message that the contact request had been accepted
1701 * @param string $target Target profile
1703 * @param integer $uid User ID
1704 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1705 * @throws \ImagickException
1707 public static function sendContactAccept($target, $id, $uid)
1709 $profile = APContact::getByURL($target);
1710 if (empty($profile['inbox'])) {
1711 Logger::warning('No inbox found for target', ['target' => $target, 'profile' => $profile]);
1715 $owner = User::getOwnerDataById($uid);
1716 $data = ['@context' => ActivityPub::CONTEXT,
1717 'id' => System::baseUrl() . '/activity/' . System::createGUID(),
1719 'actor' => $owner['url'],
1721 'id' => (string)$id,
1723 'actor' => $profile['url'],
1724 'object' => $owner['url']
1726 'instrument' => self::getService(),
1727 'to' => [$profile['url']]];
1729 Logger::debug('Sending accept to ' . $target . ' for user ' . $uid . ' with id ' . $id);
1731 $signed = LDSignature::sign($data, $owner);
1732 HTTPSignature::transmit($signed, $profile['inbox'], $uid);
1736 * Reject a contact request or terminates the contact relation
1738 * @param string $target Target profile
1740 * @param integer $uid User ID
1741 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1742 * @throws \ImagickException
1744 public static function sendContactReject($target, $id, $uid)
1746 $profile = APContact::getByURL($target);
1747 if (empty($profile['inbox'])) {
1748 Logger::warning('No inbox found for target', ['target' => $target, 'profile' => $profile]);
1752 $owner = User::getOwnerDataById($uid);
1753 $data = ['@context' => ActivityPub::CONTEXT,
1754 'id' => System::baseUrl() . '/activity/' . System::createGUID(),
1756 'actor' => $owner['url'],
1758 'id' => (string)$id,
1760 'actor' => $profile['url'],
1761 'object' => $owner['url']
1763 'instrument' => self::getService(),
1764 'to' => [$profile['url']]];
1766 Logger::debug('Sending reject to ' . $target . ' for user ' . $uid . ' with id ' . $id);
1768 $signed = LDSignature::sign($data, $owner);
1769 HTTPSignature::transmit($signed, $profile['inbox'], $uid);
1773 * Transmits a message that we don't want to follow this contact anymore
1775 * @param string $target Target profile
1776 * @param integer $uid User ID
1777 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1778 * @throws \ImagickException
1779 * @throws \Exception
1781 public static function sendContactUndo($target, $cid, $uid)
1783 $profile = APContact::getByURL($target);
1784 if (empty($profile['inbox'])) {
1785 Logger::warning('No inbox found for target', ['target' => $target, 'profile' => $profile]);
1789 $object_id = self::activityIDFromContact($cid);
1790 if (empty($object_id)) {
1794 $id = System::baseUrl() . '/activity/' . System::createGUID();
1796 $owner = User::getOwnerDataById($uid);
1797 $data = ['@context' => ActivityPub::CONTEXT,
1800 'actor' => $owner['url'],
1801 'object' => ['id' => $object_id, 'type' => 'Follow',
1802 'actor' => $owner['url'],
1803 'object' => $profile['url']],
1804 'instrument' => self::getService(),
1805 'to' => [$profile['url']]];
1807 Logger::log('Sending undo to ' . $target . ' for user ' . $uid . ' with id ' . $id, Logger::DEBUG);
1809 $signed = LDSignature::sign($data, $owner);
1810 HTTPSignature::transmit($signed, $profile['inbox'], $uid);
1813 private static function prependMentions($body, array $permission_block)
1815 if (Config::get('system', 'disable_implicit_mentions')) {
1821 foreach ($permission_block['to'] as $profile_url) {
1822 $profile = Contact::getDetailsByURL($profile_url);
1823 if (!empty($profile['addr'])
1824 && $profile['contact-type'] != Contact::TYPE_COMMUNITY
1825 && !strstr($body, $profile['addr'])
1826 && !strstr($body, $profile_url)
1828 $mentions[] = '@[url=' . $profile_url . ']' . $profile['nick'] . '[/url]';
1832 $mentions[] = $body;
1834 return implode(' ', $mentions);