3 * @copyright Copyright (C) 2020, Friendica
5 * @license GNU AGPL version 3 or any later version
7 * This program is free software: you can redistribute it and/or modify
8 * it under the terms of the GNU Affero General Public License as
9 * published by the Free Software Foundation, either version 3 of the
10 * License, or (at your option) any later version.
12 * This program is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU Affero General Public License for more details.
17 * You should have received a copy of the GNU Affero General Public License
18 * along with this program. If not, see <https://www.gnu.org/licenses/>.
22 namespace Friendica\Protocol\ActivityPub;
24 use Friendica\Content\Feature;
25 use Friendica\Content\Text\BBCode;
26 use Friendica\Content\Text\Plaintext;
27 use Friendica\Core\Cache\Duration;
28 use Friendica\Core\Logger;
29 use Friendica\Core\Protocol;
30 use Friendica\Core\System;
31 use Friendica\Database\DBA;
33 use Friendica\Model\APContact;
34 use Friendica\Model\Contact;
35 use Friendica\Model\Conversation;
36 use Friendica\Model\Item;
37 use Friendica\Model\Profile;
38 use Friendica\Model\Photo;
39 use Friendica\Model\Term;
40 use Friendica\Model\User;
41 use Friendica\Protocol\Activity;
42 use Friendica\Protocol\ActivityPub;
43 use Friendica\Util\DateTimeFormat;
44 use Friendica\Util\HTTPSignature;
45 use Friendica\Util\Images;
46 use Friendica\Util\JsonLD;
47 use Friendica\Util\LDSignature;
48 use Friendica\Util\Map;
49 use Friendica\Util\Network;
50 use Friendica\Util\XML;
52 require_once 'include/api.php';
53 require_once 'mod/share.php';
56 * ActivityPub Transmitter Protocol class
64 * collects the lost of followers of the given owner
66 * @param array $owner Owner array
67 * @param integer $page Page number
69 * @return array of owners
70 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
72 public static function getFollowers($owner, $page = null)
74 $condition = ['rel' => [Contact::FOLLOWER, Contact::FRIEND], 'network' => Protocol::FEDERATED, 'uid' => $owner['uid'],
75 'self' => false, 'deleted' => false, 'hidden' => false, 'archive' => false, 'pending' => false];
76 $count = DBA::count('contact', $condition);
78 $data = ['@context' => ActivityPub::CONTEXT];
79 $data['id'] = DI::baseUrl() . '/followers/' . $owner['nickname'];
80 $data['type'] = 'OrderedCollection';
81 $data['totalItems'] = $count;
83 // When we hide our friends we will only show the pure number but don't allow more.
84 $profile = Profile::getByUID($owner['uid']);
85 if (!empty($profile['hide-friends'])) {
90 $data['first'] = DI::baseUrl() . '/followers/' . $owner['nickname'] . '?page=1';
92 $data['type'] = 'OrderedCollectionPage';
95 $contacts = DBA::select('contact', ['url'], $condition, ['limit' => [($page - 1) * 100, 100]]);
96 while ($contact = DBA::fetch($contacts)) {
97 $list[] = $contact['url'];
99 DBA::close($contacts);
102 $data['next'] = DI::baseUrl() . '/followers/' . $owner['nickname'] . '?page=' . ($page + 1);
105 $data['partOf'] = DI::baseUrl() . '/followers/' . $owner['nickname'];
107 $data['orderedItems'] = $list;
114 * Create list of following contacts
116 * @param array $owner Owner array
117 * @param integer $page Page numbe
119 * @return array of following contacts
120 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
122 public static function getFollowing($owner, $page = null)
124 $condition = ['rel' => [Contact::SHARING, Contact::FRIEND], 'network' => Protocol::FEDERATED, 'uid' => $owner['uid'],
125 'self' => false, 'deleted' => false, 'hidden' => false, 'archive' => false, 'pending' => false];
126 $count = DBA::count('contact', $condition);
128 $data = ['@context' => ActivityPub::CONTEXT];
129 $data['id'] = DI::baseUrl() . '/following/' . $owner['nickname'];
130 $data['type'] = 'OrderedCollection';
131 $data['totalItems'] = $count;
133 // When we hide our friends we will only show the pure number but don't allow more.
134 $profile = Profile::getByUID($owner['uid']);
135 if (!empty($profile['hide-friends'])) {
140 $data['first'] = DI::baseUrl() . '/following/' . $owner['nickname'] . '?page=1';
142 $data['type'] = 'OrderedCollectionPage';
145 $contacts = DBA::select('contact', ['url'], $condition, ['limit' => [($page - 1) * 100, 100]]);
146 while ($contact = DBA::fetch($contacts)) {
147 $list[] = $contact['url'];
149 DBA::close($contacts);
152 $data['next'] = DI::baseUrl() . '/following/' . $owner['nickname'] . '?page=' . ($page + 1);
155 $data['partOf'] = DI::baseUrl() . '/following/' . $owner['nickname'];
157 $data['orderedItems'] = $list;
164 * Public posts for the given owner
166 * @param array $owner Owner array
167 * @param integer $page Page numbe
169 * @return array of posts
170 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
171 * @throws \ImagickException
173 public static function getOutbox($owner, $page = null)
175 $public_contact = Contact::getIdForURL($owner['url'], 0, true);
177 $condition = ['uid' => 0, 'contact-id' => $public_contact, 'author-id' => $public_contact,
178 'private' => [Item::PUBLIC, Item::UNLISTED], 'gravity' => [GRAVITY_PARENT, GRAVITY_COMMENT],
179 'deleted' => false, 'visible' => true, 'moderated' => false];
180 $count = DBA::count('item', $condition);
182 $data = ['@context' => ActivityPub::CONTEXT];
183 $data['id'] = DI::baseUrl() . '/outbox/' . $owner['nickname'];
184 $data['type'] = 'OrderedCollection';
185 $data['totalItems'] = $count;
188 $data['first'] = DI::baseUrl() . '/outbox/' . $owner['nickname'] . '?page=1';
190 $data['type'] = 'OrderedCollectionPage';
193 $condition['parent-network'] = Protocol::NATIVE_SUPPORT;
195 $items = Item::select(['id'], $condition, ['limit' => [($page - 1) * 20, 20], 'order' => ['created' => true]]);
196 while ($item = Item::fetch($items)) {
197 $activity = self::createActivityFromItem($item['id'], true);
198 $activity['type'] = $activity['type'] == 'Update' ? 'Create' : $activity['type'];
200 // Only list "Create" activity objects here, no reshares
201 if (!empty($activity['object']) && ($activity['type'] == 'Create')) {
202 $list[] = $activity['object'];
207 $data['next'] = DI::baseUrl() . '/outbox/' . $owner['nickname'] . '?page=' . ($page + 1);
210 $data['partOf'] = DI::baseUrl() . '/outbox/' . $owner['nickname'];
212 $data['orderedItems'] = $list;
219 * Return the service array containing information the used software and it's url
221 * @return array with service data
223 private static function getService()
225 return ['type' => 'Service',
226 'name' => FRIENDICA_PLATFORM . " '" . FRIENDICA_CODENAME . "' " . FRIENDICA_VERSION . '-' . DB_UPDATE_VERSION,
227 'url' => DI::baseUrl()->get()];
231 * Return the ActivityPub profile of the given user
233 * @param integer $uid User ID
234 * @return array with profile data
235 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
237 public static function getProfile($uid)
239 $condition = ['uid' => $uid, 'blocked' => false, 'account_expired' => false,
240 'account_removed' => false, 'verified' => true];
241 $fields = ['guid', 'nickname', 'pubkey', 'account-type', 'page-flags'];
242 $user = DBA::selectFirst('user', $fields, $condition);
243 if (!DBA::isResult($user)) {
247 $fields = ['locality', 'region', 'country-name'];
248 $profile = DBA::selectFirst('profile', $fields, ['uid' => $uid]);
249 if (!DBA::isResult($profile)) {
253 $fields = ['name', 'url', 'location', 'about', 'avatar', 'photo'];
254 $contact = DBA::selectFirst('contact', $fields, ['uid' => $uid, 'self' => true]);
255 if (!DBA::isResult($contact)) {
259 $data = ['@context' => ActivityPub::CONTEXT];
260 $data['id'] = $contact['url'];
261 $data['diaspora:guid'] = $user['guid'];
262 $data['type'] = ActivityPub::ACCOUNT_TYPES[$user['account-type']];
263 $data['following'] = DI::baseUrl() . '/following/' . $user['nickname'];
264 $data['followers'] = DI::baseUrl() . '/followers/' . $user['nickname'];
265 $data['inbox'] = DI::baseUrl() . '/inbox/' . $user['nickname'];
266 $data['outbox'] = DI::baseUrl() . '/outbox/' . $user['nickname'];
267 $data['preferredUsername'] = $user['nickname'];
268 $data['name'] = $contact['name'];
269 $data['vcard:hasAddress'] = ['@type' => 'vcard:Home', 'vcard:country-name' => $profile['country-name'],
270 'vcard:region' => $profile['region'], 'vcard:locality' => $profile['locality']];
271 $data['summary'] = BBCode::convert($contact['about'], false);
272 $data['url'] = $contact['url'];
273 $data['manuallyApprovesFollowers'] = in_array($user['page-flags'], [User::PAGE_FLAGS_NORMAL, User::PAGE_FLAGS_PRVGROUP]);
274 $data['publicKey'] = ['id' => $contact['url'] . '#main-key',
275 'owner' => $contact['url'],
276 'publicKeyPem' => $user['pubkey']];
277 $data['endpoints'] = ['sharedInbox' => DI::baseUrl() . '/inbox'];
278 $data['icon'] = ['type' => 'Image',
279 'url' => $contact['photo']];
281 $data['generator'] = self::getService();
283 // tags: https://kitty.town/@inmysocks/100656097926961126.json
288 * @param string $username
290 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
292 public static function getDeletedUser($username)
295 '@context' => ActivityPub::CONTEXT,
296 'id' => DI::baseUrl() . '/profile/' . $username,
297 'type' => 'Tombstone',
298 'published' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
299 'updated' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
300 'deleted' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
305 * Returns an array with permissions of a given item array
309 * @return array with permissions
310 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
311 * @throws \ImagickException
313 private static function fetchPermissionBlockFromConversation($item)
315 if (empty($item['thr-parent'])) {
319 $condition = ['item-uri' => $item['thr-parent'], 'protocol' => Conversation::PARCEL_ACTIVITYPUB];
320 $conversation = DBA::selectFirst('conversation', ['source'], $condition);
321 if (!DBA::isResult($conversation)) {
325 $activity = json_decode($conversation['source'], true);
327 $actor = JsonLD::fetchElement($activity, 'actor', 'id');
328 $profile = APContact::getByURL($actor);
330 $item_profile = APContact::getByURL($item['author-link']);
331 $exclude[] = $item['author-link'];
333 if ($item['gravity'] == GRAVITY_PARENT) {
334 $exclude[] = $item['owner-link'];
337 $permissions['to'][] = $actor;
339 foreach (['to', 'cc', 'bto', 'bcc'] as $element) {
340 if (empty($activity[$element])) {
343 if (is_string($activity[$element])) {
344 $activity[$element] = [$activity[$element]];
347 foreach ($activity[$element] as $receiver) {
348 if (empty($receiver)) {
352 if (!empty($profile['followers']) && $receiver == $profile['followers'] && !empty($item_profile['followers'])) {
353 $permissions[$element][] = $item_profile['followers'];
354 } elseif (!in_array($receiver, $exclude)) {
355 $permissions[$element][] = $receiver;
363 * Creates an array of permissions from an item thread
365 * @param array $item Item array
366 * @param boolean $blindcopy addressing via "bcc" or "cc"?
367 * @param integer $last_id Last item id for adding receivers
368 * @param boolean $forum_mode "true" means that we are sending content to a forum
370 * @return array with permission data
371 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
372 * @throws \ImagickException
374 private static function createPermissionBlockForItem($item, $blindcopy, $last_id = 0, $forum_mode = false)
377 $last_id = $item['id'];
382 // Check if we should always deliver our stuff via BCC
383 if (!empty($item['uid'])) {
384 $profile = Profile::getByUID($item['uid']);
385 if (!empty($profile)) {
386 $always_bcc = $profile['hide-friends'];
390 if (DI::config()->get('system', 'ap_always_bcc')) {
394 if (self::isAnnounce($item) || DI::config()->get('debug', 'total_ap_delivery')) {
395 // Will be activated in a later step
396 $networks = Protocol::FEDERATED;
398 // For now only send to these contacts:
399 $networks = [Protocol::ACTIVITYPUB, Protocol::OSTATUS];
402 $data = ['to' => [], 'cc' => [], 'bcc' => []];
404 if ($item['gravity'] == GRAVITY_PARENT) {
405 $actor_profile = APContact::getByURL($item['owner-link']);
407 $actor_profile = APContact::getByURL($item['author-link']);
410 $terms = Term::tagArrayFromItemId($item['id'], [Term::MENTION, Term::IMPLICIT_MENTION]);
412 if ($item['private'] != Item::PRIVATE) {
413 // Directly mention the original author upon a quoted reshare.
414 // Else just ensure that the original author receives the reshare.
415 $announce = self::getAnnounceArray($item);
416 if (!empty($announce['comment'])) {
417 $data['to'][] = $announce['actor']['url'];
418 } elseif (!empty($announce)) {
419 $data['cc'][] = $announce['actor']['url'];
422 $data = array_merge($data, self::fetchPermissionBlockFromConversation($item));
424 // Check if the item is completely public or unlisted
425 if ($item['private'] == Item::PUBLIC) {
426 $data['to'][] = ActivityPub::PUBLIC_COLLECTION;
428 $data['cc'][] = ActivityPub::PUBLIC_COLLECTION;
431 foreach ($terms as $term) {
432 $profile = APContact::getByURL($term['url'], false);
433 if (!empty($profile)) {
434 $data['to'][] = $profile['url'];
438 $receiver_list = Item::enumeratePermissions($item, true);
440 foreach ($terms as $term) {
441 $cid = Contact::getIdForURL($term['url'], $item['uid']);
442 if (!empty($cid) && in_array($cid, $receiver_list)) {
443 $contact = DBA::selectFirst('contact', ['url', 'network', 'protocol'], ['id' => $cid]);
444 if (!DBA::isResult($contact) || (!in_array($contact['network'], $networks) && ($contact['protocol'] != Protocol::ACTIVITYPUB))) {
448 if (!empty($profile = APContact::getByURL($contact['url'], false))) {
449 $data['to'][] = $profile['url'];
454 foreach ($receiver_list as $receiver) {
455 $contact = DBA::selectFirst('contact', ['url', 'hidden', 'network', 'protocol'], ['id' => $receiver]);
456 if (!DBA::isResult($contact) || (!in_array($contact['network'], $networks) && ($contact['protocol'] != Protocol::ACTIVITYPUB))) {
460 if (!empty($profile = APContact::getByURL($contact['url'], false))) {
461 if ($contact['hidden'] || $always_bcc) {
462 $data['bcc'][] = $profile['url'];
464 $data['cc'][] = $profile['url'];
470 if (!empty($item['parent'])) {
471 $parents = Item::select(['id', 'author-link', 'owner-link', 'gravity', 'uri'], ['parent' => $item['parent']]);
472 while ($parent = Item::fetch($parents)) {
473 if ($parent['gravity'] == GRAVITY_PARENT) {
474 $profile = APContact::getByURL($parent['owner-link'], false);
475 if (!empty($profile)) {
476 if ($item['gravity'] != GRAVITY_PARENT) {
477 // Comments to forums are directed to the forum
478 // But comments to forums aren't directed to the followers collection
479 if ($profile['type'] == 'Group') {
480 $data['to'][] = $profile['url'];
482 $data['cc'][] = $profile['url'];
483 if (($item['private'] != Item::PRIVATE) && !empty($actor_profile['followers'])) {
484 $data['cc'][] = $actor_profile['followers'];
488 // Public thread parent post always are directed to the followers
489 if (($item['private'] != Item::PRIVATE) && !$forum_mode) {
490 $data['cc'][] = $actor_profile['followers'];
496 // Don't include data from future posts
497 if ($parent['id'] >= $last_id) {
501 $profile = APContact::getByURL($parent['author-link'], false);
502 if (!empty($profile)) {
503 if (($profile['type'] == 'Group') || ($parent['uri'] == $item['thr-parent'])) {
504 $data['to'][] = $profile['url'];
506 $data['cc'][] = $profile['url'];
510 DBA::close($parents);
513 $data['to'] = array_unique($data['to']);
514 $data['cc'] = array_unique($data['cc']);
515 $data['bcc'] = array_unique($data['bcc']);
517 if (($key = array_search($item['author-link'], $data['to'])) !== false) {
518 unset($data['to'][$key]);
521 if (($key = array_search($item['author-link'], $data['cc'])) !== false) {
522 unset($data['cc'][$key]);
525 if (($key = array_search($item['author-link'], $data['bcc'])) !== false) {
526 unset($data['bcc'][$key]);
529 foreach ($data['to'] as $to) {
530 if (($key = array_search($to, $data['cc'])) !== false) {
531 unset($data['cc'][$key]);
534 if (($key = array_search($to, $data['bcc'])) !== false) {
535 unset($data['bcc'][$key]);
539 foreach ($data['cc'] as $cc) {
540 if (($key = array_search($cc, $data['bcc'])) !== false) {
541 unset($data['bcc'][$key]);
545 $receivers = ['to' => array_values($data['to']), 'cc' => array_values($data['cc']), 'bcc' => array_values($data['bcc'])];
548 unset($receivers['bcc']);
555 * Check if an inbox is archived
557 * @param string $url Inbox url
559 * @return boolean "true" if inbox is archived
561 private static function archivedInbox($url)
563 return DBA::exists('inbox-status', ['url' => $url, 'archive' => true]);
567 * Fetches a list of inboxes of followers of a given user
569 * @param integer $uid User ID
570 * @param boolean $personal fetch personal inboxes
572 * @return array of follower inboxes
573 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
574 * @throws \ImagickException
576 public static function fetchTargetInboxesforUser($uid, $personal = false)
580 if (DI::config()->get('debug', 'total_ap_delivery')) {
581 // Will be activated in a later step
582 $networks = Protocol::FEDERATED;
584 // For now only send to these contacts:
585 $networks = [Protocol::ACTIVITYPUB, Protocol::OSTATUS];
588 $condition = ['uid' => $uid, 'archive' => false, 'pending' => false];
591 $condition['rel'] = [Contact::FOLLOWER, Contact::FRIEND];
594 $contacts = DBA::select('contact', ['url', 'network', 'protocol'], $condition);
595 while ($contact = DBA::fetch($contacts)) {
596 if (Contact::isLocal($contact['url'])) {
600 if (!in_array($contact['network'], $networks) && ($contact['protocol'] != Protocol::ACTIVITYPUB)) {
604 if (Network::isUrlBlocked($contact['url'])) {
608 $profile = APContact::getByURL($contact['url'], false);
609 if (!empty($profile)) {
610 if (empty($profile['sharedinbox']) || $personal) {
611 $target = $profile['inbox'];
613 $target = $profile['sharedinbox'];
615 if (!self::archivedInbox($target)) {
616 $inboxes[$target] = $target;
620 DBA::close($contacts);
626 * Fetches an array of inboxes for the given item and user
628 * @param array $item Item array
629 * @param integer $uid User ID
630 * @param boolean $personal fetch personal inboxes
631 * @param integer $last_id Last item id for adding receivers
632 * @param boolean $forum_mode "true" means that we are sending content to a forum
633 * @return array with inboxes
634 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
635 * @throws \ImagickException
637 public static function fetchTargetInboxes($item, $uid, $personal = false, $last_id = 0, $forum_mode = false)
639 $permissions = self::createPermissionBlockForItem($item, true, $last_id, $forum_mode);
640 if (empty($permissions)) {
646 if ($item['gravity'] == GRAVITY_ACTIVITY) {
647 $item_profile = APContact::getByURL($item['author-link'], false);
649 $item_profile = APContact::getByURL($item['owner-link'], false);
652 foreach (['to', 'cc', 'bto', 'bcc'] as $element) {
653 if (empty($permissions[$element])) {
657 $blindcopy = in_array($element, ['bto', 'bcc']);
659 foreach ($permissions[$element] as $receiver) {
660 if (empty($receiver) || Network::isUrlBlocked($receiver)) {
664 if ($receiver == $item_profile['followers']) {
665 $inboxes = array_merge($inboxes, self::fetchTargetInboxesforUser($uid, $personal));
667 if (Contact::isLocal($receiver)) {
671 $profile = APContact::getByURL($receiver, false);
672 if (!empty($profile)) {
673 if (empty($profile['sharedinbox']) || $personal || $blindcopy) {
674 $target = $profile['inbox'];
676 $target = $profile['sharedinbox'];
678 if (!self::archivedInbox($target)) {
679 $inboxes[$target] = $target;
690 * Creates an array in the structure of the item table for a given mail id
692 * @param integer $mail_id
697 public static function ItemArrayFromMail($mail_id)
699 $mail = DBA::selectFirst('mail', [], ['id' => $mail_id]);
700 if (!DBA::isResult($mail)) {
704 $reply = DBA::selectFirst('mail', ['uri'], ['parent-uri' => $mail['parent-uri'], 'reply' => false]);
706 // Making the post more compatible for Mastodon by:
707 // - Making it a note and not an article (no title)
708 // - Moving the title into the "summary" field that is used as a "content warning"
709 $mail['body'] = '[abstract]' . $mail['title'] . "[/abstract]\n" . $mail['body'];
712 $mail['author-link'] = $mail['owner-link'] = $mail['from-url'];
713 $mail['allow_cid'] = '<'.$mail['contact-id'].'>';
714 $mail['allow_gid'] = '';
715 $mail['deny_cid'] = '';
716 $mail['deny_gid'] = '';
717 $mail['private'] = true;
718 $mail['deleted'] = false;
719 $mail['edited'] = $mail['created'];
720 $mail['plink'] = $mail['uri'];
721 $mail['thr-parent'] = $reply['uri'];
722 $mail['gravity'] = ($mail['reply'] ? GRAVITY_COMMENT: GRAVITY_PARENT);
724 $mail['event-type'] = '';
725 $mail['attach'] = '';
733 * Creates an activity array for a given mail id
735 * @param integer $mail_id
736 * @param boolean $object_mode Is the activity item is used inside another object?
738 * @return array of activity
741 public static function createActivityFromMail($mail_id, $object_mode = false)
743 $mail = self::ItemArrayFromMail($mail_id);
744 $object = self::createNote($mail);
747 $data = ['@context' => ActivityPub::CONTEXT];
752 $data['id'] = $mail['uri'] . '#Create';
753 $data['type'] = 'Create';
754 $data['actor'] = $mail['author-link'];
755 $data['published'] = DateTimeFormat::utc($mail['created'] . '+00:00', DateTimeFormat::ATOM);
756 $data['instrument'] = self::getService();
757 $data = array_merge($data, self::createPermissionBlockForItem($mail, true));
759 if (empty($data['to']) && !empty($data['cc'])) {
760 $data['to'] = $data['cc'];
763 if (empty($data['to']) && !empty($data['bcc'])) {
764 $data['to'] = $data['bcc'];
770 $object['to'] = $data['to'];
771 $object['tag'] = [['type' => 'Mention', 'href' => $object['to'][0], 'name' => '']];
773 unset($object['cc']);
774 unset($object['bcc']);
776 $data['directMessage'] = true;
778 $data['object'] = $object;
780 $owner = User::getOwnerDataById($mail['uid']);
782 if (!$object_mode && !empty($owner)) {
783 return LDSignature::sign($data, $owner);
790 * Returns the activity type of a given item
794 * @return string with activity type
795 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
796 * @throws \ImagickException
798 private static function getTypeOfItem($item)
802 // Only check for a reshare, if it is a real reshare and no quoted reshare
803 if (strpos($item['body'], "[share") === 0) {
804 $announce = self::getAnnounceArray($item);
805 $reshared = !empty($announce);
810 } elseif ($item['verb'] == Activity::POST) {
811 if ($item['created'] == $item['edited']) {
816 } elseif ($item['verb'] == Activity::LIKE) {
818 } elseif ($item['verb'] == Activity::DISLIKE) {
820 } elseif ($item['verb'] == Activity::ATTEND) {
822 } elseif ($item['verb'] == Activity::ATTENDNO) {
824 } elseif ($item['verb'] == Activity::ATTENDMAYBE) {
825 $type = 'TentativeAccept';
826 } elseif ($item['verb'] == Activity::FOLLOW) {
828 } elseif ($item['verb'] == Activity::TAG) {
838 * Creates the activity or fetches it from the cache
840 * @param integer $item_id
841 * @param boolean $force Force new cache entry
843 * @return array with the activity
846 public static function createCachedActivityFromItem($item_id, $force = false)
848 $cachekey = 'APDelivery:createActivity:' . $item_id;
851 $data = DI::cache()->get($cachekey);
852 if (!is_null($data)) {
857 $data = ActivityPub\Transmitter::createActivityFromItem($item_id);
859 DI::cache()->set($cachekey, $data, Duration::QUARTER_HOUR);
864 * Creates an activity array for a given item id
866 * @param integer $item_id
867 * @param boolean $object_mode Is the activity item is used inside another object?
869 * @return array of activity
872 public static function createActivityFromItem($item_id, $object_mode = false)
874 $item = Item::selectFirst([], ['id' => $item_id, 'parent-network' => Protocol::NATIVE_SUPPORT]);
876 if (!DBA::isResult($item)) {
880 if ($item['wall'] && ($item['uri'] == $item['parent-uri'])) {
881 $owner = User::getOwnerDataById($item['uid']);
882 if (($owner['account-type'] == User::ACCOUNT_TYPE_COMMUNITY) && ($item['author-link'] != $owner['url'])) {
885 // Disguise forum posts as reshares. Will later be converted to a real announce
886 $item['body'] = share_header($item['author-name'], $item['author-link'], $item['author-avatar'],
887 $item['guid'], $item['created'], $item['plink']) . $item['body'] . '[/share]';
892 $condition = ['item-uri' => $item['uri'], 'protocol' => Conversation::PARCEL_ACTIVITYPUB];
893 $conversation = DBA::selectFirst('conversation', ['source'], $condition);
894 if (DBA::isResult($conversation)) {
895 $data = json_decode($conversation['source'], true);
901 $type = self::getTypeOfItem($item);
905 $data = ['@context' => ActivityPub::CONTEXT];
907 if ($item['deleted'] && ($item['gravity'] == GRAVITY_ACTIVITY)) {
909 } elseif ($item['deleted']) {
916 $data['id'] = $item['uri'] . '#' . $type;
917 $data['type'] = $type;
919 if (Item::isForumPost($item) && ($type != 'Announce')) {
920 $data['actor'] = $item['author-link'];
922 $data['actor'] = $item['owner-link'];
925 $data['published'] = DateTimeFormat::utc($item['created'] . '+00:00', DateTimeFormat::ATOM);
927 $data['instrument'] = self::getService();
929 $data = array_merge($data, self::createPermissionBlockForItem($item, false));
931 if (in_array($data['type'], ['Create', 'Update', 'Delete'])) {
932 $data['object'] = self::createNote($item);
933 } elseif ($data['type'] == 'Add') {
934 $data = self::createAddTag($item, $data);
935 } elseif ($data['type'] == 'Announce') {
936 $data = self::createAnnounce($item, $data);
937 } elseif ($data['type'] == 'Follow') {
938 $data['object'] = $item['parent-uri'];
939 } elseif ($data['type'] == 'Undo') {
940 $data['object'] = self::createActivityFromItem($item_id, true);
942 $data['diaspora:guid'] = $item['guid'];
943 if (!empty($item['signed_text'])) {
944 $data['diaspora:like'] = $item['signed_text'];
946 $data['object'] = $item['thr-parent'];
949 if (!empty($item['contact-uid'])) {
950 $uid = $item['contact-uid'];
955 $owner = User::getOwnerDataById($uid);
957 if (!$object_mode && !empty($owner)) {
958 return LDSignature::sign($data, $owner);
963 /// @todo Create "conversation" entry
967 * Creates a location entry for a given item array
971 * @return array with location array
973 private static function createLocation($item)
975 $location = ['type' => 'Place'];
977 if (!empty($item['location'])) {
978 $location['name'] = $item['location'];
983 if (empty($item['coord'])) {
984 $coord = Map::getCoordinates($item['location']);
986 $coords = explode(' ', $item['coord']);
987 if (count($coords) == 2) {
988 $coord = ['lat' => $coords[0], 'lon' => $coords[1]];
992 if (!empty($coord['lat']) && !empty($coord['lon'])) {
993 $location['latitude'] = $coord['lat'];
994 $location['longitude'] = $coord['lon'];
1001 * Returns a tag array for a given item array
1003 * @param array $item
1005 * @return array of tags
1006 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1008 private static function createTagList($item)
1012 $terms = Term::tagArrayFromItemId($item['id'], [Term::HASHTAG, Term::MENTION, Term::IMPLICIT_MENTION]);
1013 foreach ($terms as $term) {
1014 if ($term['type'] == Term::HASHTAG) {
1015 $url = DI::baseUrl() . '/search?tag=' . urlencode($term['term']);
1016 $tags[] = ['type' => 'Hashtag', 'href' => $url, 'name' => '#' . $term['term']];
1017 } elseif ($term['type'] == Term::MENTION || $term['type'] == Term::IMPLICIT_MENTION) {
1018 $contact = Contact::getDetailsByURL($term['url']);
1019 if (!empty($contact['addr'])) {
1020 $mention = '@' . $contact['addr'];
1022 $mention = '@' . $term['url'];
1025 $tags[] = ['type' => 'Mention', 'href' => $term['url'], 'name' => $mention];
1029 $announce = self::getAnnounceArray($item);
1030 // Mention the original author upon commented reshares
1031 if (!empty($announce['comment'])) {
1032 $tags[] = ['type' => 'Mention', 'href' => $announce['actor']['url'], 'name' => '@' . $announce['actor']['addr']];
1039 * Adds attachment data to the JSON document
1041 * @param array $item Data of the item that is to be posted
1042 * @param string $type Object type
1044 * @return array with attachment data
1045 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1047 private static function createAttachmentList($item, $type)
1051 // Currently deactivated, since it creates side effects on Mastodon and Pleroma.
1052 // It will be reactivated, once this cleared.
1054 $attach_data = BBCode::getAttachmentData($item['body']);
1055 if (!empty($attach_data['url'])) {
1056 $attachment = ['type' => 'Page',
1057 'mediaType' => 'text/html',
1058 'url' => $attach_data['url']];
1060 if (!empty($attach_data['title'])) {
1061 $attachment['name'] = $attach_data['title'];
1064 if (!empty($attach_data['description'])) {
1065 $attachment['summary'] = $attach_data['description'];
1068 if (!empty($attach_data['image'])) {
1069 $imgdata = Images::getInfoFromURLCached($attach_data['image']);
1071 $attachment['icon'] = ['type' => 'Image',
1072 'mediaType' => $imgdata['mime'],
1073 'width' => $imgdata[0],
1074 'height' => $imgdata[1],
1075 'url' => $attach_data['image']];
1079 $attachments[] = $attachment;
1082 $arr = explode('[/attach],', $item['attach']);
1084 foreach ($arr as $r) {
1086 $cnt = preg_match('|\[attach\]href=\"(.*?)\" length=\"(.*?)\" type=\"(.*?)\" title=\"(.*?)\"|', $r, $matches);
1088 $attributes = ['type' => 'Document',
1089 'mediaType' => $matches[3],
1090 'url' => $matches[1],
1093 if (trim($matches[4]) != '') {
1094 $attributes['name'] = trim($matches[4]);
1097 $attachments[] = $attributes;
1102 if ($type != 'Note') {
1103 return $attachments;
1106 // Simplify image codes
1107 $body = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '[img]$3[/img]', $item['body']);
1109 // Grab all pictures without alternative descriptions and create attachments out of them
1110 if (preg_match_all("/\[img\]([^\[\]]*)\[\/img\]/Usi", $body, $pictures)) {
1111 foreach ($pictures[1] as $picture) {
1112 $imgdata = Images::getInfoFromURLCached($picture);
1114 $attachments[] = ['type' => 'Document',
1115 'mediaType' => $imgdata['mime'],
1122 // Grab all pictures with alternative description and create attachments out of them
1123 if (preg_match_all("/\[img=([^\[\]]*)\]([^\[\]]*)\[\/img\]/Usi", $body, $pictures, PREG_SET_ORDER)) {
1124 foreach ($pictures as $picture) {
1125 $imgdata = Images::getInfoFromURLCached($picture[1]);
1127 $attachments[] = ['type' => 'Document',
1128 'mediaType' => $imgdata['mime'],
1129 'url' => $picture[1],
1130 'name' => $picture[2]];
1135 return $attachments;
1139 * Callback function to replace a Friendica style mention in a mention that is used on AP
1141 * @param array $match Matching values for the callback
1142 * @return string Replaced mention
1143 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1145 private static function mentionCallback($match)
1147 if (empty($match[1])) {
1151 $data = Contact::getDetailsByURL($match[1]);
1152 if (empty($data['nick'])) {
1156 return '@[url=' . $data['url'] . ']' . $data['nick'] . '[/url]';
1160 * Remove image elements since they are added as attachment
1162 * @param string $body
1164 * @return string with removed images
1166 private static function removePictures($body)
1168 // Simplify image codes
1169 $body = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '[img]$3[/img]', $body);
1170 $body = preg_replace("/\[img\=(.*?)\](.*?)\[\/img\]/ism", '[img]$1[/img]', $body);
1172 // Now remove local links
1173 $body = preg_replace_callback(
1174 '/\[url=([^\[\]]*)\]\[img\](.*)\[\/img\]\[\/url\]/Usi',
1176 // We remove the link when it is a link to a local photo page
1177 if (Photo::isLocalPage($match[1])) {
1180 // otherwise we just return the link
1181 return '[url]' . $match[1] . '[/url]';
1186 // Remove all pictures
1187 $body = preg_replace("/\[img\]([^\[\]]*)\[\/img\]/Usi", '', $body);
1193 * Fetches the "context" value for a givem item array from the "conversation" table
1195 * @param array $item
1197 * @return string with context url
1198 * @throws \Exception
1200 private static function fetchContextURLForItem($item)
1202 $conversation = DBA::selectFirst('conversation', ['conversation-href', 'conversation-uri'], ['item-uri' => $item['parent-uri']]);
1203 if (DBA::isResult($conversation) && !empty($conversation['conversation-href'])) {
1204 $context_uri = $conversation['conversation-href'];
1205 } elseif (DBA::isResult($conversation) && !empty($conversation['conversation-uri'])) {
1206 $context_uri = $conversation['conversation-uri'];
1208 $context_uri = $item['parent-uri'] . '#context';
1210 return $context_uri;
1214 * Returns if the post contains sensitive content ("nsfw")
1216 * @param integer $item_id
1219 * @throws \Exception
1221 private static function isSensitive($item_id)
1223 $condition = ['otype' => Term::OBJECT_TYPE_POST, 'oid' => $item_id, 'type' => Term::HASHTAG, 'term' => 'nsfw'];
1224 return DBA::exists('term', $condition);
1228 * Creates event data
1230 * @param array $item
1232 * @return array with the event data
1233 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1235 public static function createEvent($item)
1238 $event['name'] = $item['event-summary'];
1239 $event['content'] = BBCode::convert($item['event-desc'], false, 9);
1240 $event['startTime'] = DateTimeFormat::utc($item['event-start'] . '+00:00', DateTimeFormat::ATOM);
1242 if (!$item['event-nofinish']) {
1243 $event['endTime'] = DateTimeFormat::utc($item['event-finish'] . '+00:00', DateTimeFormat::ATOM);
1246 if (!empty($item['event-location'])) {
1247 $item['location'] = $item['event-location'];
1248 $event['location'] = self::createLocation($item);
1255 * Creates a note/article object array
1257 * @param array $item
1259 * @return array with the object data
1260 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1261 * @throws \ImagickException
1263 public static function createNote($item)
1269 if ($item['event-type'] == 'event') {
1271 } elseif (!empty($item['title'])) {
1277 if ($item['deleted']) {
1278 $type = 'Tombstone';
1282 $data['id'] = $item['uri'];
1283 $data['type'] = $type;
1285 if ($item['deleted']) {
1289 $data['summary'] = BBCode::toPlaintext(BBCode::getAbstract($item['body'], Protocol::ACTIVITYPUB));
1291 if ($item['uri'] != $item['thr-parent']) {
1292 $data['inReplyTo'] = $item['thr-parent'];
1294 $data['inReplyTo'] = null;
1297 $data['diaspora:guid'] = $item['guid'];
1298 $data['published'] = DateTimeFormat::utc($item['created'] . '+00:00', DateTimeFormat::ATOM);
1300 if ($item['created'] != $item['edited']) {
1301 $data['updated'] = DateTimeFormat::utc($item['edited'] . '+00:00', DateTimeFormat::ATOM);
1304 $data['url'] = $item['plink'];
1305 $data['attributedTo'] = $item['author-link'];
1306 $data['sensitive'] = self::isSensitive($item['id']);
1307 $data['context'] = self::fetchContextURLForItem($item);
1309 if (!empty($item['title'])) {
1310 $data['name'] = BBCode::toPlaintext($item['title'], false);
1313 $permission_block = self::createPermissionBlockForItem($item, false);
1315 $body = $item['body'];
1317 if (empty($item['uid']) || !Feature::isEnabled($item['uid'], 'explicit_mentions')) {
1318 $body = self::prependMentions($body, $permission_block);
1321 if ($type == 'Note') {
1322 $body = self::removePictures($body);
1323 } elseif (($type == 'Article') && empty($data['summary'])) {
1324 $data['summary'] = BBCode::toPlaintext(Plaintext::shorten(self::removePictures($body), 1000));
1327 if ($type == 'Event') {
1328 $data = array_merge($data, self::createEvent($item));
1330 $regexp = "/[@!]\[url\=([^\[\]]*)\].*?\[\/url\]/ism";
1331 $body = preg_replace_callback($regexp, ['self', 'mentionCallback'], $body);
1333 $data['content'] = BBCode::convert($body, false, 9);
1336 // The regular "content" field does contain a minimized HTML. This is done since systems like
1337 // Mastodon has got problems with - for example - embedded pictures.
1338 // The contentMap does contain the unmodified HTML.
1339 $language = self::getLanguage($item);
1340 if (!empty($language)) {
1341 $regexp = "/[@!]\[url\=([^\[\]]*)\].*?\[\/url\]/ism";
1342 $richbody = preg_replace_callback($regexp, ['self', 'mentionCallback'], $item['body']);
1343 $richbody = BBCode::removeAttachment($richbody);
1345 $data['contentMap'][$language] = BBCode::convert($richbody, false);
1348 $data['source'] = ['content' => $item['body'], 'mediaType' => "text/bbcode"];
1350 if (!empty($item['signed_text']) && ($item['uri'] != $item['thr-parent'])) {
1351 $data['diaspora:comment'] = $item['signed_text'];
1354 $data['attachment'] = self::createAttachmentList($item, $type);
1355 $data['tag'] = self::createTagList($item);
1357 if (empty($data['location']) && (!empty($item['coord']) || !empty($item['location']))) {
1358 $data['location'] = self::createLocation($item);
1361 if (!empty($item['app'])) {
1362 $data['generator'] = ['type' => 'Application', 'name' => $item['app']];
1365 $data = array_merge($data, $permission_block);
1371 * Fetches the language from the post, the user or the system.
1373 * @param array $item
1375 * @return string language string
1377 private static function getLanguage(array $item)
1379 // Try to fetch the language from the post itself
1380 if (!empty($item['language'])) {
1381 $languages = array_keys(json_decode($item['language'], true));
1382 if (!empty($languages[0])) {
1383 return $languages[0];
1387 // Otherwise use the user's language
1388 if (!empty($item['uid'])) {
1389 $user = DBA::selectFirst('user', ['language'], ['uid' => $item['uid']]);
1390 if (!empty($user['language'])) {
1391 return $user['language'];
1395 // And finally just use the system language
1396 return DI::config()->get('system', 'language');
1400 * Creates an an "add tag" entry
1402 * @param array $item
1403 * @param array $data activity data
1405 * @return array with activity data for adding tags
1406 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1407 * @throws \ImagickException
1409 private static function createAddTag($item, $data)
1411 $object = XML::parseString($item['object']);
1412 $target = XML::parseString($item["target"]);
1414 $data['diaspora:guid'] = $item['guid'];
1415 $data['actor'] = $item['author-link'];
1416 $data['target'] = (string)$target->id;
1417 $data['summary'] = BBCode::toPlaintext($item['body']);
1418 $data['object'] = ['id' => (string)$object->id, 'type' => 'tag', 'name' => (string)$object->title, 'content' => (string)$object->content];
1424 * Creates an announce object entry
1426 * @param array $item
1427 * @param array $data activity data
1429 * @return array with activity data
1430 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1431 * @throws \ImagickException
1433 private static function createAnnounce($item, $data)
1435 $orig_body = $item['body'];
1436 $announce = self::getAnnounceArray($item);
1437 if (empty($announce)) {
1438 $data['type'] = 'Create';
1439 $data['object'] = self::createNote($item);
1443 if (empty($announce['comment'])) {
1444 // Pure announce, without a quote
1445 $data['type'] = 'Announce';
1446 $data['object'] = $announce['object']['uri'];
1451 $data['type'] = 'Create';
1452 $item['body'] = $announce['comment'] . "\n" . $announce['object']['plink'];
1453 $data['object'] = self::createNote($item);
1455 /// @todo Finally descide how to implement this in AP. This is a possible way:
1456 $data['object']['attachment'][] = self::createNote($announce['object']);
1458 $data['object']['source']['content'] = $orig_body;
1463 * Return announce related data if the item is an annunce
1465 * @param array $item
1469 public static function getAnnounceArray($item)
1471 $reshared = Item::getShareArray($item);
1472 if (empty($reshared['guid'])) {
1476 $reshared_item = Item::selectFirst([], ['guid' => $reshared['guid']]);
1477 if (!DBA::isResult($reshared_item)) {
1481 if (!in_array($reshared_item['network'], [Protocol::ACTIVITYPUB, Protocol::DFRN])) {
1485 $profile = APContact::getByURL($reshared_item['author-link'], false);
1486 if (empty($profile)) {
1490 return ['object' => $reshared_item, 'actor' => $profile, 'comment' => $reshared['comment']];
1494 * Checks if the provided item array is an announce
1496 * @param array $item
1500 public static function isAnnounce($item)
1502 $announce = self::getAnnounceArray($item);
1503 if (empty($announce)) {
1507 return empty($announce['comment']);
1511 * Creates an activity id for a given contact id
1513 * @param integer $cid Contact ID of target
1515 * @return bool|string activity id
1517 public static function activityIDFromContact($cid)
1519 $contact = DBA::selectFirst('contact', ['uid', 'id', 'created'], ['id' => $cid]);
1520 if (!DBA::isResult($contact)) {
1524 $hash = hash('ripemd128', $contact['uid'].'-'.$contact['id'].'-'.$contact['created']);
1525 $uuid = substr($hash, 0, 8). '-' . substr($hash, 8, 4) . '-' . substr($hash, 12, 4) . '-' . substr($hash, 16, 4) . '-' . substr($hash, 20, 12);
1526 return DI::baseUrl() . '/activity/' . $uuid;
1530 * Transmits a contact suggestion to a given inbox
1532 * @param integer $uid User ID
1533 * @param string $inbox Target inbox
1534 * @param integer $suggestion_id Suggestion ID
1536 * @return boolean was the transmission successful?
1537 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1539 public static function sendContactSuggestion($uid, $inbox, $suggestion_id)
1541 $owner = User::getOwnerDataById($uid);
1543 $suggestion = DI::fsuggest()->getById($suggestion_id);
1545 $data = ['@context' => ActivityPub::CONTEXT,
1546 'id' => DI::baseUrl() . '/activity/' . System::createGUID(),
1547 'type' => 'Announce',
1548 'actor' => $owner['url'],
1549 'object' => $suggestion->url,
1550 'content' => $suggestion->note,
1551 'instrument' => self::getService(),
1552 'to' => [ActivityPub::PUBLIC_COLLECTION],
1555 $signed = LDSignature::sign($data, $owner);
1557 Logger::log('Deliver profile deletion for user ' . $uid . ' to ' . $inbox . ' via ActivityPub', Logger::DEBUG);
1558 return HTTPSignature::transmit($signed, $inbox, $uid);
1562 * Transmits a profile relocation to a given inbox
1564 * @param integer $uid User ID
1565 * @param string $inbox Target inbox
1567 * @return boolean was the transmission successful?
1568 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1570 public static function sendProfileRelocation($uid, $inbox)
1572 $owner = User::getOwnerDataById($uid);
1574 $data = ['@context' => ActivityPub::CONTEXT,
1575 'id' => DI::baseUrl() . '/activity/' . System::createGUID(),
1576 'type' => 'dfrn:relocate',
1577 'actor' => $owner['url'],
1578 'object' => $owner['url'],
1579 'published' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
1580 'instrument' => self::getService(),
1581 'to' => [ActivityPub::PUBLIC_COLLECTION],
1584 $signed = LDSignature::sign($data, $owner);
1586 Logger::log('Deliver profile relocation for user ' . $uid . ' to ' . $inbox . ' via ActivityPub', Logger::DEBUG);
1587 return HTTPSignature::transmit($signed, $inbox, $uid);
1591 * Transmits a profile deletion to a given inbox
1593 * @param integer $uid User ID
1594 * @param string $inbox Target inbox
1596 * @return boolean was the transmission successful?
1597 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1599 public static function sendProfileDeletion($uid, $inbox)
1601 $owner = User::getOwnerDataById($uid);
1603 if (empty($owner)) {
1604 Logger::error('No owner data found, the deletion message cannot be processed.', ['user' => $uid]);
1608 if (empty($owner['uprvkey'])) {
1609 Logger::error('No private key for owner found, the deletion message cannot be processed.', ['user' => $uid]);
1613 $data = ['@context' => ActivityPub::CONTEXT,
1614 'id' => DI::baseUrl() . '/activity/' . System::createGUID(),
1616 'actor' => $owner['url'],
1617 'object' => $owner['url'],
1618 'published' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
1619 'instrument' => self::getService(),
1620 'to' => [ActivityPub::PUBLIC_COLLECTION],
1623 $signed = LDSignature::sign($data, $owner);
1625 Logger::log('Deliver profile deletion for user ' . $uid . ' to ' . $inbox . ' via ActivityPub', Logger::DEBUG);
1626 return HTTPSignature::transmit($signed, $inbox, $uid);
1630 * Transmits a profile change to a given inbox
1632 * @param integer $uid User ID
1633 * @param string $inbox Target inbox
1635 * @return boolean was the transmission successful?
1636 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1637 * @throws \ImagickException
1639 public static function sendProfileUpdate($uid, $inbox)
1641 $owner = User::getOwnerDataById($uid);
1642 $profile = APContact::getByURL($owner['url']);
1644 $data = ['@context' => ActivityPub::CONTEXT,
1645 'id' => DI::baseUrl() . '/activity/' . System::createGUID(),
1647 'actor' => $owner['url'],
1648 'object' => self::getProfile($uid),
1649 'published' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
1650 'instrument' => self::getService(),
1651 'to' => [$profile['followers']],
1654 $signed = LDSignature::sign($data, $owner);
1656 Logger::log('Deliver profile update for user ' . $uid . ' to ' . $inbox . ' via ActivityPub', Logger::DEBUG);
1657 return HTTPSignature::transmit($signed, $inbox, $uid);
1661 * Transmits a given activity to a target
1663 * @param string $activity Type name
1664 * @param string $target Target profile
1665 * @param integer $uid User ID
1667 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1668 * @throws \ImagickException
1669 * @throws \Exception
1671 public static function sendActivity($activity, $target, $uid, $id = '')
1673 $profile = APContact::getByURL($target);
1674 if (empty($profile['inbox'])) {
1675 Logger::warning('No inbox found for target', ['target' => $target, 'profile' => $profile]);
1679 $owner = User::getOwnerDataById($uid);
1682 $id = DI::baseUrl() . '/activity/' . System::createGUID();
1685 $data = ['@context' => ActivityPub::CONTEXT,
1687 'type' => $activity,
1688 'actor' => $owner['url'],
1689 'object' => $profile['url'],
1690 'instrument' => self::getService(),
1691 'to' => [$profile['url']]];
1693 Logger::log('Sending activity ' . $activity . ' to ' . $target . ' for user ' . $uid, Logger::DEBUG);
1695 $signed = LDSignature::sign($data, $owner);
1696 return HTTPSignature::transmit($signed, $profile['inbox'], $uid);
1700 * Transmits a "follow object" activity to a target
1701 * This is a preparation for sending automated "follow" requests when receiving "Announce" messages
1703 * @param string $object Object URL
1704 * @param string $target Target profile
1705 * @param integer $uid User ID
1707 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1708 * @throws \ImagickException
1709 * @throws \Exception
1711 public static function sendFollowObject($object, $target, $uid = 0)
1713 $profile = APContact::getByURL($target);
1714 if (empty($profile['inbox'])) {
1715 Logger::warning('No inbox found for target', ['target' => $target, 'profile' => $profile]);
1720 // Fetch the list of administrators
1721 $admin_mail = explode(',', str_replace(' ', '', DI::config()->get('config', 'admin_email')));
1723 // We need to use some user as a sender. It doesn't care who it will send. We will use an administrator account.
1724 $condition = ['verified' => true, 'blocked' => false, 'account_removed' => false, 'account_expired' => false, 'email' => $admin_mail];
1725 $first_user = DBA::selectFirst('user', ['uid'], $condition);
1726 $uid = $first_user['uid'];
1729 $condition = ['verb' => Activity::FOLLOW, 'uid' => 0, 'parent-uri' => $object,
1730 'author-id' => Contact::getPublicIdByUserId($uid)];
1731 if (Item::exists($condition)) {
1732 Logger::log('Follow for ' . $object . ' for user ' . $uid . ' does already exist.', Logger::DEBUG);
1736 $owner = User::getOwnerDataById($uid);
1738 $data = ['@context' => ActivityPub::CONTEXT,
1739 'id' => DI::baseUrl() . '/activity/' . System::createGUID(),
1741 'actor' => $owner['url'],
1742 'object' => $object,
1743 'instrument' => self::getService(),
1744 'to' => [$profile['url']]];
1746 Logger::log('Sending follow ' . $object . ' to ' . $target . ' for user ' . $uid, Logger::DEBUG);
1748 $signed = LDSignature::sign($data, $owner);
1749 return HTTPSignature::transmit($signed, $profile['inbox'], $uid);
1753 * Transmit a message that the contact request had been accepted
1755 * @param string $target Target profile
1757 * @param integer $uid User ID
1758 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1759 * @throws \ImagickException
1761 public static function sendContactAccept($target, $id, $uid)
1763 $profile = APContact::getByURL($target);
1764 if (empty($profile['inbox'])) {
1765 Logger::warning('No inbox found for target', ['target' => $target, 'profile' => $profile]);
1769 $owner = User::getOwnerDataById($uid);
1770 $data = ['@context' => ActivityPub::CONTEXT,
1771 'id' => DI::baseUrl() . '/activity/' . System::createGUID(),
1773 'actor' => $owner['url'],
1775 'id' => (string)$id,
1777 'actor' => $profile['url'],
1778 'object' => $owner['url']
1780 'instrument' => self::getService(),
1781 'to' => [$profile['url']]];
1783 Logger::debug('Sending accept to ' . $target . ' for user ' . $uid . ' with id ' . $id);
1785 $signed = LDSignature::sign($data, $owner);
1786 HTTPSignature::transmit($signed, $profile['inbox'], $uid);
1790 * Reject a contact request or terminates the contact relation
1792 * @param string $target Target profile
1794 * @param integer $uid User ID
1795 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1796 * @throws \ImagickException
1798 public static function sendContactReject($target, $id, $uid)
1800 $profile = APContact::getByURL($target);
1801 if (empty($profile['inbox'])) {
1802 Logger::warning('No inbox found for target', ['target' => $target, 'profile' => $profile]);
1806 $owner = User::getOwnerDataById($uid);
1807 $data = ['@context' => ActivityPub::CONTEXT,
1808 'id' => DI::baseUrl() . '/activity/' . System::createGUID(),
1810 'actor' => $owner['url'],
1812 'id' => (string)$id,
1814 'actor' => $profile['url'],
1815 'object' => $owner['url']
1817 'instrument' => self::getService(),
1818 'to' => [$profile['url']]];
1820 Logger::debug('Sending reject to ' . $target . ' for user ' . $uid . ' with id ' . $id);
1822 $signed = LDSignature::sign($data, $owner);
1823 HTTPSignature::transmit($signed, $profile['inbox'], $uid);
1827 * Transmits a message that we don't want to follow this contact anymore
1829 * @param string $target Target profile
1830 * @param integer $uid User ID
1831 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1832 * @throws \ImagickException
1833 * @throws \Exception
1835 public static function sendContactUndo($target, $cid, $uid)
1837 $profile = APContact::getByURL($target);
1838 if (empty($profile['inbox'])) {
1839 Logger::warning('No inbox found for target', ['target' => $target, 'profile' => $profile]);
1843 $object_id = self::activityIDFromContact($cid);
1844 if (empty($object_id)) {
1848 $id = DI::baseUrl() . '/activity/' . System::createGUID();
1850 $owner = User::getOwnerDataById($uid);
1851 $data = ['@context' => ActivityPub::CONTEXT,
1854 'actor' => $owner['url'],
1855 'object' => ['id' => $object_id, 'type' => 'Follow',
1856 'actor' => $owner['url'],
1857 'object' => $profile['url']],
1858 'instrument' => self::getService(),
1859 'to' => [$profile['url']]];
1861 Logger::log('Sending undo to ' . $target . ' for user ' . $uid . ' with id ' . $id, Logger::DEBUG);
1863 $signed = LDSignature::sign($data, $owner);
1864 HTTPSignature::transmit($signed, $profile['inbox'], $uid);
1867 private static function prependMentions($body, array $permission_block)
1869 if (DI::config()->get('system', 'disable_implicit_mentions')) {
1875 foreach ($permission_block['to'] as $profile_url) {
1876 $profile = Contact::getDetailsByURL($profile_url);
1877 if (!empty($profile['addr'])
1878 && $profile['contact-type'] != Contact::TYPE_COMMUNITY
1879 && !strstr($body, $profile['addr'])
1880 && !strstr($body, $profile_url)
1882 $mentions[] = '@[url=' . $profile_url . ']' . $profile['nick'] . '[/url]';
1886 $mentions[] = $body;
1888 return implode(' ', $mentions);