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\ItemURI;
38 use Friendica\Model\Profile;
39 use Friendica\Model\Photo;
40 use Friendica\Model\Tag;
41 use Friendica\Model\User;
42 use Friendica\Protocol\Activity;
43 use Friendica\Protocol\ActivityPub;
44 use Friendica\Util\DateTimeFormat;
45 use Friendica\Util\HTTPSignature;
46 use Friendica\Util\Images;
47 use Friendica\Util\JsonLD;
48 use Friendica\Util\LDSignature;
49 use Friendica\Util\Map;
50 use Friendica\Util\Network;
51 use Friendica\Util\XML;
53 require_once 'include/api.php';
54 require_once 'mod/share.php';
57 * ActivityPub Transmitter Protocol class
65 * collects the lost of followers of the given owner
67 * @param array $owner Owner array
68 * @param integer $page Page number
70 * @return array of owners
71 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
73 public static function getFollowers($owner, $page = null)
75 $condition = ['rel' => [Contact::FOLLOWER, Contact::FRIEND], 'network' => Protocol::FEDERATED, 'uid' => $owner['uid'],
76 'self' => false, 'deleted' => false, 'hidden' => false, 'archive' => false, 'pending' => false];
77 $count = DBA::count('contact', $condition);
79 $data = ['@context' => ActivityPub::CONTEXT];
80 $data['id'] = DI::baseUrl() . '/followers/' . $owner['nickname'];
81 $data['type'] = 'OrderedCollection';
82 $data['totalItems'] = $count;
84 // When we hide our friends we will only show the pure number but don't allow more.
85 $profile = Profile::getByUID($owner['uid']);
86 if (!empty($profile['hide-friends'])) {
91 $data['first'] = DI::baseUrl() . '/followers/' . $owner['nickname'] . '?page=1';
93 $data['type'] = 'OrderedCollectionPage';
96 $contacts = DBA::select('contact', ['url'], $condition, ['limit' => [($page - 1) * 100, 100]]);
97 while ($contact = DBA::fetch($contacts)) {
98 $list[] = $contact['url'];
100 DBA::close($contacts);
103 $data['next'] = DI::baseUrl() . '/followers/' . $owner['nickname'] . '?page=' . ($page + 1);
106 $data['partOf'] = DI::baseUrl() . '/followers/' . $owner['nickname'];
108 $data['orderedItems'] = $list;
115 * Create list of following contacts
117 * @param array $owner Owner array
118 * @param integer $page Page numbe
120 * @return array of following contacts
121 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
123 public static function getFollowing($owner, $page = null)
125 $condition = ['rel' => [Contact::SHARING, Contact::FRIEND], 'network' => Protocol::FEDERATED, 'uid' => $owner['uid'],
126 'self' => false, 'deleted' => false, 'hidden' => false, 'archive' => false, 'pending' => false];
127 $count = DBA::count('contact', $condition);
129 $data = ['@context' => ActivityPub::CONTEXT];
130 $data['id'] = DI::baseUrl() . '/following/' . $owner['nickname'];
131 $data['type'] = 'OrderedCollection';
132 $data['totalItems'] = $count;
134 // When we hide our friends we will only show the pure number but don't allow more.
135 $profile = Profile::getByUID($owner['uid']);
136 if (!empty($profile['hide-friends'])) {
141 $data['first'] = DI::baseUrl() . '/following/' . $owner['nickname'] . '?page=1';
143 $data['type'] = 'OrderedCollectionPage';
146 $contacts = DBA::select('contact', ['url'], $condition, ['limit' => [($page - 1) * 100, 100]]);
147 while ($contact = DBA::fetch($contacts)) {
148 $list[] = $contact['url'];
150 DBA::close($contacts);
153 $data['next'] = DI::baseUrl() . '/following/' . $owner['nickname'] . '?page=' . ($page + 1);
156 $data['partOf'] = DI::baseUrl() . '/following/' . $owner['nickname'];
158 $data['orderedItems'] = $list;
165 * Public posts for the given owner
167 * @param array $owner Owner array
168 * @param integer $page Page numbe
170 * @return array of posts
171 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
172 * @throws \ImagickException
174 public static function getOutbox($owner, $page = null)
176 $public_contact = Contact::getIdForURL($owner['url'], 0, true);
178 $condition = ['uid' => 0, 'contact-id' => $public_contact, 'author-id' => $public_contact,
179 'private' => [Item::PUBLIC, Item::UNLISTED], 'gravity' => [GRAVITY_PARENT, GRAVITY_COMMENT],
180 'deleted' => false, 'visible' => true, 'moderated' => false];
181 $count = DBA::count('item', $condition);
183 $data = ['@context' => ActivityPub::CONTEXT];
184 $data['id'] = DI::baseUrl() . '/outbox/' . $owner['nickname'];
185 $data['type'] = 'OrderedCollection';
186 $data['totalItems'] = $count;
189 $data['first'] = DI::baseUrl() . '/outbox/' . $owner['nickname'] . '?page=1';
191 $data['type'] = 'OrderedCollectionPage';
194 $condition['parent-network'] = Protocol::NATIVE_SUPPORT;
196 $items = Item::select(['id'], $condition, ['limit' => [($page - 1) * 20, 20], 'order' => ['created' => true]]);
197 while ($item = Item::fetch($items)) {
198 $activity = self::createActivityFromItem($item['id'], true);
199 $activity['type'] = $activity['type'] == 'Update' ? 'Create' : $activity['type'];
201 // Only list "Create" activity objects here, no reshares
202 if (!empty($activity['object']) && ($activity['type'] == 'Create')) {
203 $list[] = $activity['object'];
208 $data['next'] = DI::baseUrl() . '/outbox/' . $owner['nickname'] . '?page=' . ($page + 1);
211 $data['partOf'] = DI::baseUrl() . '/outbox/' . $owner['nickname'];
213 $data['orderedItems'] = $list;
220 * Return the service array containing information the used software and it's url
222 * @return array with service data
224 private static function getService()
226 return ['type' => 'Service',
227 'name' => FRIENDICA_PLATFORM . " '" . FRIENDICA_CODENAME . "' " . FRIENDICA_VERSION . '-' . DB_UPDATE_VERSION,
228 'url' => DI::baseUrl()->get()];
232 * Return the ActivityPub profile of the given user
234 * @param integer $uid User ID
235 * @return array with profile data
236 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
238 public static function getProfile($uid)
240 $condition = ['uid' => $uid, 'blocked' => false, 'account_expired' => false,
241 'account_removed' => false, 'verified' => true];
242 $fields = ['guid', 'nickname', 'pubkey', 'account-type', 'page-flags'];
243 $user = DBA::selectFirst('user', $fields, $condition);
244 if (!DBA::isResult($user)) {
248 $fields = ['locality', 'region', 'country-name'];
249 $profile = DBA::selectFirst('profile', $fields, ['uid' => $uid]);
250 if (!DBA::isResult($profile)) {
254 $fields = ['name', 'url', 'location', 'about', 'avatar', 'photo'];
255 $contact = DBA::selectFirst('contact', $fields, ['uid' => $uid, 'self' => true]);
256 if (!DBA::isResult($contact)) {
260 $data = ['@context' => ActivityPub::CONTEXT];
261 $data['id'] = $contact['url'];
262 $data['diaspora:guid'] = $user['guid'];
263 $data['type'] = ActivityPub::ACCOUNT_TYPES[$user['account-type']];
264 $data['following'] = DI::baseUrl() . '/following/' . $user['nickname'];
265 $data['followers'] = DI::baseUrl() . '/followers/' . $user['nickname'];
266 $data['inbox'] = DI::baseUrl() . '/inbox/' . $user['nickname'];
267 $data['outbox'] = DI::baseUrl() . '/outbox/' . $user['nickname'];
268 $data['preferredUsername'] = $user['nickname'];
269 $data['name'] = $contact['name'];
270 $data['vcard:hasAddress'] = ['@type' => 'vcard:Home', 'vcard:country-name' => $profile['country-name'],
271 'vcard:region' => $profile['region'], 'vcard:locality' => $profile['locality']];
272 $data['summary'] = BBCode::convert($contact['about'], false);
273 $data['url'] = $contact['url'];
274 $data['manuallyApprovesFollowers'] = in_array($user['page-flags'], [User::PAGE_FLAGS_NORMAL, User::PAGE_FLAGS_PRVGROUP]);
275 $data['publicKey'] = ['id' => $contact['url'] . '#main-key',
276 'owner' => $contact['url'],
277 'publicKeyPem' => $user['pubkey']];
278 $data['endpoints'] = ['sharedInbox' => DI::baseUrl() . '/inbox'];
279 $data['icon'] = ['type' => 'Image',
280 'url' => $contact['photo']];
282 $data['generator'] = self::getService();
284 // tags: https://kitty.town/@inmysocks/100656097926961126.json
289 * @param string $username
291 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
293 public static function getDeletedUser($username)
296 '@context' => ActivityPub::CONTEXT,
297 'id' => DI::baseUrl() . '/profile/' . $username,
298 'type' => 'Tombstone',
299 'published' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
300 'updated' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
301 'deleted' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
306 * Returns an array with permissions of a given item array
310 * @return array with permissions
311 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
312 * @throws \ImagickException
314 private static function fetchPermissionBlockFromConversation($item)
316 if (empty($item['thr-parent'])) {
320 $condition = ['item-uri' => $item['thr-parent'], 'protocol' => Conversation::PARCEL_ACTIVITYPUB];
321 $conversation = DBA::selectFirst('conversation', ['source'], $condition);
322 if (!DBA::isResult($conversation)) {
326 $activity = json_decode($conversation['source'], true);
328 $actor = JsonLD::fetchElement($activity, 'actor', 'id');
329 $profile = APContact::getByURL($actor);
331 $item_profile = APContact::getByURL($item['author-link']);
332 $exclude[] = $item['author-link'];
334 if ($item['gravity'] == GRAVITY_PARENT) {
335 $exclude[] = $item['owner-link'];
338 $permissions['to'][] = $actor;
340 foreach (['to', 'cc', 'bto', 'bcc'] as $element) {
341 if (empty($activity[$element])) {
344 if (is_string($activity[$element])) {
345 $activity[$element] = [$activity[$element]];
348 foreach ($activity[$element] as $receiver) {
349 if (empty($receiver)) {
353 if (!empty($profile['followers']) && $receiver == $profile['followers'] && !empty($item_profile['followers'])) {
354 $permissions[$element][] = $item_profile['followers'];
355 } elseif (!in_array($receiver, $exclude)) {
356 $permissions[$element][] = $receiver;
364 * Creates an array of permissions from an item thread
366 * @param array $item Item array
367 * @param boolean $blindcopy addressing via "bcc" or "cc"?
368 * @param integer $last_id Last item id for adding receivers
369 * @param boolean $forum_mode "true" means that we are sending content to a forum
371 * @return array with permission data
372 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
373 * @throws \ImagickException
375 private static function createPermissionBlockForItem($item, $blindcopy, $last_id = 0, $forum_mode = false)
378 $last_id = $item['id'];
383 // Check if we should always deliver our stuff via BCC
384 if (!empty($item['uid'])) {
385 $profile = Profile::getByUID($item['uid']);
386 if (!empty($profile)) {
387 $always_bcc = $profile['hide-friends'];
391 if (DI::config()->get('system', 'ap_always_bcc')) {
395 if (self::isAnnounce($item) || DI::config()->get('debug', 'total_ap_delivery')) {
396 // Will be activated in a later step
397 $networks = Protocol::FEDERATED;
399 // For now only send to these contacts:
400 $networks = [Protocol::ACTIVITYPUB, Protocol::OSTATUS];
403 $data = ['to' => [], 'cc' => [], 'bcc' => []];
405 if ($item['gravity'] == GRAVITY_PARENT) {
406 $actor_profile = APContact::getByURL($item['owner-link']);
408 $actor_profile = APContact::getByURL($item['author-link']);
411 $terms = Tag::getByURIId($item['uri-id'], [Tag::MENTION, Tag::IMPLICIT_MENTION, Tag::EXCLUSIVE_MENTION]);
413 if ($item['private'] != Item::PRIVATE) {
414 // Directly mention the original author upon a quoted reshare.
415 // Else just ensure that the original author receives the reshare.
416 $announce = self::getAnnounceArray($item);
417 if (!empty($announce['comment'])) {
418 $data['to'][] = $announce['actor']['url'];
419 } elseif (!empty($announce)) {
420 $data['cc'][] = $announce['actor']['url'];
423 $data = array_merge($data, self::fetchPermissionBlockFromConversation($item));
425 // Check if the item is completely public or unlisted
426 if ($item['private'] == Item::PUBLIC) {
427 $data['to'][] = ActivityPub::PUBLIC_COLLECTION;
429 $data['cc'][] = ActivityPub::PUBLIC_COLLECTION;
432 foreach ($terms as $term) {
433 $profile = APContact::getByURL($term['url'], false);
434 if (!empty($profile)) {
435 $data['to'][] = $profile['url'];
439 $receiver_list = Item::enumeratePermissions($item, true);
441 foreach ($terms as $term) {
442 $cid = Contact::getIdForURL($term['url'], $item['uid']);
443 if (!empty($cid) && in_array($cid, $receiver_list)) {
444 $contact = DBA::selectFirst('contact', ['url', 'network', 'protocol'], ['id' => $cid]);
445 if (!DBA::isResult($contact) || (!in_array($contact['network'], $networks) && ($contact['protocol'] != Protocol::ACTIVITYPUB))) {
449 if (!empty($profile = APContact::getByURL($contact['url'], false))) {
450 $data['to'][] = $profile['url'];
455 foreach ($receiver_list as $receiver) {
456 $contact = DBA::selectFirst('contact', ['url', 'hidden', 'network', 'protocol'], ['id' => $receiver]);
457 if (!DBA::isResult($contact) || (!in_array($contact['network'], $networks) && ($contact['protocol'] != Protocol::ACTIVITYPUB))) {
461 if (!empty($profile = APContact::getByURL($contact['url'], false))) {
462 if ($contact['hidden'] || $always_bcc) {
463 $data['bcc'][] = $profile['url'];
465 $data['cc'][] = $profile['url'];
471 if (!empty($item['parent'])) {
472 $parents = Item::select(['id', 'author-link', 'owner-link', 'gravity', 'uri'], ['parent' => $item['parent']]);
473 while ($parent = Item::fetch($parents)) {
474 if ($parent['gravity'] == GRAVITY_PARENT) {
475 $profile = APContact::getByURL($parent['owner-link'], false);
476 if (!empty($profile)) {
477 if ($item['gravity'] != GRAVITY_PARENT) {
478 // Comments to forums are directed to the forum
479 // But comments to forums aren't directed to the followers collection
480 if ($profile['type'] == 'Group') {
481 $data['to'][] = $profile['url'];
483 $data['cc'][] = $profile['url'];
484 if (($item['private'] != Item::PRIVATE) && !empty($actor_profile['followers'])) {
485 $data['cc'][] = $actor_profile['followers'];
489 // Public thread parent post always are directed to the followers
490 if (($item['private'] != Item::PRIVATE) && !$forum_mode) {
491 $data['cc'][] = $actor_profile['followers'];
497 // Don't include data from future posts
498 if ($parent['id'] >= $last_id) {
502 $profile = APContact::getByURL($parent['author-link'], false);
503 if (!empty($profile)) {
504 if (($profile['type'] == 'Group') || ($parent['uri'] == $item['thr-parent'])) {
505 $data['to'][] = $profile['url'];
507 $data['cc'][] = $profile['url'];
511 DBA::close($parents);
514 $data['to'] = array_unique($data['to']);
515 $data['cc'] = array_unique($data['cc']);
516 $data['bcc'] = array_unique($data['bcc']);
518 if (($key = array_search($item['author-link'], $data['to'])) !== false) {
519 unset($data['to'][$key]);
522 if (($key = array_search($item['author-link'], $data['cc'])) !== false) {
523 unset($data['cc'][$key]);
526 if (($key = array_search($item['author-link'], $data['bcc'])) !== false) {
527 unset($data['bcc'][$key]);
530 foreach ($data['to'] as $to) {
531 if (($key = array_search($to, $data['cc'])) !== false) {
532 unset($data['cc'][$key]);
535 if (($key = array_search($to, $data['bcc'])) !== false) {
536 unset($data['bcc'][$key]);
540 foreach ($data['cc'] as $cc) {
541 if (($key = array_search($cc, $data['bcc'])) !== false) {
542 unset($data['bcc'][$key]);
546 $receivers = ['to' => array_values($data['to']), 'cc' => array_values($data['cc']), 'bcc' => array_values($data['bcc'])];
549 unset($receivers['bcc']);
556 * Check if an inbox is archived
558 * @param string $url Inbox url
560 * @return boolean "true" if inbox is archived
562 private static function archivedInbox($url)
564 return DBA::exists('inbox-status', ['url' => $url, 'archive' => true]);
568 * Fetches a list of inboxes of followers of a given user
570 * @param integer $uid User ID
571 * @param boolean $personal fetch personal inboxes
573 * @return array of follower inboxes
574 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
575 * @throws \ImagickException
577 public static function fetchTargetInboxesforUser($uid, $personal = false)
581 if (DI::config()->get('debug', 'total_ap_delivery')) {
582 // Will be activated in a later step
583 $networks = Protocol::FEDERATED;
585 // For now only send to these contacts:
586 $networks = [Protocol::ACTIVITYPUB, Protocol::OSTATUS];
589 $condition = ['uid' => $uid, 'archive' => false, 'pending' => false];
592 $condition['rel'] = [Contact::FOLLOWER, Contact::FRIEND];
595 $contacts = DBA::select('contact', ['url', 'network', 'protocol'], $condition);
596 while ($contact = DBA::fetch($contacts)) {
597 if (Contact::isLocal($contact['url'])) {
601 if (!in_array($contact['network'], $networks) && ($contact['protocol'] != Protocol::ACTIVITYPUB)) {
605 if (Network::isUrlBlocked($contact['url'])) {
609 $profile = APContact::getByURL($contact['url'], false);
610 if (!empty($profile)) {
611 if (empty($profile['sharedinbox']) || $personal) {
612 $target = $profile['inbox'];
614 $target = $profile['sharedinbox'];
616 if (!self::archivedInbox($target)) {
617 $inboxes[$target] = $target;
621 DBA::close($contacts);
627 * Fetches an array of inboxes for the given item and user
629 * @param array $item Item array
630 * @param integer $uid User ID
631 * @param boolean $personal fetch personal inboxes
632 * @param integer $last_id Last item id for adding receivers
633 * @param boolean $forum_mode "true" means that we are sending content to a forum
634 * @return array with inboxes
635 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
636 * @throws \ImagickException
638 public static function fetchTargetInboxes($item, $uid, $personal = false, $last_id = 0, $forum_mode = false)
640 $permissions = self::createPermissionBlockForItem($item, true, $last_id, $forum_mode);
641 if (empty($permissions)) {
647 if ($item['gravity'] == GRAVITY_ACTIVITY) {
648 $item_profile = APContact::getByURL($item['author-link'], false);
650 $item_profile = APContact::getByURL($item['owner-link'], false);
653 foreach (['to', 'cc', 'bto', 'bcc'] as $element) {
654 if (empty($permissions[$element])) {
658 $blindcopy = in_array($element, ['bto', 'bcc']);
660 foreach ($permissions[$element] as $receiver) {
661 if (empty($receiver) || Network::isUrlBlocked($receiver)) {
665 if ($receiver == $item_profile['followers']) {
666 $inboxes = array_merge($inboxes, self::fetchTargetInboxesforUser($uid, $personal));
668 if (Contact::isLocal($receiver)) {
672 $profile = APContact::getByURL($receiver, false);
673 if (!empty($profile)) {
674 if (empty($profile['sharedinbox']) || $personal || $blindcopy) {
675 $target = $profile['inbox'];
677 $target = $profile['sharedinbox'];
679 if (!self::archivedInbox($target)) {
680 $inboxes[$target] = $target;
691 * Creates an array in the structure of the item table for a given mail id
693 * @param integer $mail_id
698 public static function ItemArrayFromMail($mail_id)
700 $mail = DBA::selectFirst('mail', [], ['id' => $mail_id]);
701 if (!DBA::isResult($mail)) {
705 $mail['uri-id'] = ItemURI::insert(['uri' => $mail['uri'], 'guid' => $mail['guid']]);
707 $reply = DBA::selectFirst('mail', ['uri'], ['parent-uri' => $mail['parent-uri'], 'reply' => false]);
709 // Making the post more compatible for Mastodon by:
710 // - Making it a note and not an article (no title)
711 // - Moving the title into the "summary" field that is used as a "content warning"
712 $mail['body'] = '[abstract]' . $mail['title'] . "[/abstract]\n" . $mail['body'];
715 $mail['author-link'] = $mail['owner-link'] = $mail['from-url'];
716 $mail['allow_cid'] = '<'.$mail['contact-id'].'>';
717 $mail['allow_gid'] = '';
718 $mail['deny_cid'] = '';
719 $mail['deny_gid'] = '';
720 $mail['private'] = true;
721 $mail['deleted'] = false;
722 $mail['edited'] = $mail['created'];
723 $mail['plink'] = $mail['uri'];
724 $mail['thr-parent'] = $reply['uri'];
725 $mail['gravity'] = ($mail['reply'] ? GRAVITY_COMMENT: GRAVITY_PARENT);
727 $mail['event-type'] = '';
728 $mail['attach'] = '';
736 * Creates an activity array for a given mail id
738 * @param integer $mail_id
739 * @param boolean $object_mode Is the activity item is used inside another object?
741 * @return array of activity
744 public static function createActivityFromMail($mail_id, $object_mode = false)
746 $mail = self::ItemArrayFromMail($mail_id);
747 $object = self::createNote($mail);
750 $data = ['@context' => ActivityPub::CONTEXT];
755 $data['id'] = $mail['uri'] . '#Create';
756 $data['type'] = 'Create';
757 $data['actor'] = $mail['author-link'];
758 $data['published'] = DateTimeFormat::utc($mail['created'] . '+00:00', DateTimeFormat::ATOM);
759 $data['instrument'] = self::getService();
760 $data = array_merge($data, self::createPermissionBlockForItem($mail, true));
762 if (empty($data['to']) && !empty($data['cc'])) {
763 $data['to'] = $data['cc'];
766 if (empty($data['to']) && !empty($data['bcc'])) {
767 $data['to'] = $data['bcc'];
773 $object['to'] = $data['to'];
774 $object['tag'] = [['type' => 'Mention', 'href' => $object['to'][0], 'name' => '']];
776 unset($object['cc']);
777 unset($object['bcc']);
779 $data['directMessage'] = true;
781 $data['object'] = $object;
783 $owner = User::getOwnerDataById($mail['uid']);
785 if (!$object_mode && !empty($owner)) {
786 return LDSignature::sign($data, $owner);
793 * Returns the activity type of a given item
797 * @return string with activity type
798 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
799 * @throws \ImagickException
801 private static function getTypeOfItem($item)
805 // Only check for a reshare, if it is a real reshare and no quoted reshare
806 if (strpos($item['body'], "[share") === 0) {
807 $announce = self::getAnnounceArray($item);
808 $reshared = !empty($announce);
813 } elseif ($item['verb'] == Activity::POST) {
814 if ($item['created'] == $item['edited']) {
819 } elseif ($item['verb'] == Activity::LIKE) {
821 } elseif ($item['verb'] == Activity::DISLIKE) {
823 } elseif ($item['verb'] == Activity::ATTEND) {
825 } elseif ($item['verb'] == Activity::ATTENDNO) {
827 } elseif ($item['verb'] == Activity::ATTENDMAYBE) {
828 $type = 'TentativeAccept';
829 } elseif ($item['verb'] == Activity::FOLLOW) {
831 } elseif ($item['verb'] == Activity::TAG) {
841 * Creates the activity or fetches it from the cache
843 * @param integer $item_id
844 * @param boolean $force Force new cache entry
846 * @return array with the activity
849 public static function createCachedActivityFromItem($item_id, $force = false)
851 $cachekey = 'APDelivery:createActivity:' . $item_id;
854 $data = DI::cache()->get($cachekey);
855 if (!is_null($data)) {
860 $data = ActivityPub\Transmitter::createActivityFromItem($item_id);
862 DI::cache()->set($cachekey, $data, Duration::QUARTER_HOUR);
867 * Creates an activity array for a given item id
869 * @param integer $item_id
870 * @param boolean $object_mode Is the activity item is used inside another object?
872 * @return array of activity
875 public static function createActivityFromItem($item_id, $object_mode = false)
877 $item = Item::selectFirst([], ['id' => $item_id, 'parent-network' => Protocol::NATIVE_SUPPORT]);
879 if (!DBA::isResult($item)) {
883 if ($item['wall'] && ($item['uri'] == $item['parent-uri'])) {
884 $owner = User::getOwnerDataById($item['uid']);
885 if (($owner['account-type'] == User::ACCOUNT_TYPE_COMMUNITY) && ($item['author-link'] != $owner['url'])) {
888 // Disguise forum posts as reshares. Will later be converted to a real announce
889 $item['body'] = share_header($item['author-name'], $item['author-link'], $item['author-avatar'],
890 $item['guid'], $item['created'], $item['plink']) . $item['body'] . '[/share]';
895 $condition = ['item-uri' => $item['uri'], 'protocol' => Conversation::PARCEL_ACTIVITYPUB];
896 $conversation = DBA::selectFirst('conversation', ['source'], $condition);
897 if (DBA::isResult($conversation)) {
898 $data = json_decode($conversation['source'], true);
904 $type = self::getTypeOfItem($item);
908 $data = ['@context' => ActivityPub::CONTEXT];
910 if ($item['deleted'] && ($item['gravity'] == GRAVITY_ACTIVITY)) {
912 } elseif ($item['deleted']) {
919 $data['id'] = $item['uri'] . '#' . $type;
920 $data['type'] = $type;
922 if (Item::isForumPost($item) && ($type != 'Announce')) {
923 $data['actor'] = $item['author-link'];
925 $data['actor'] = $item['owner-link'];
928 $data['published'] = DateTimeFormat::utc($item['created'] . '+00:00', DateTimeFormat::ATOM);
930 $data['instrument'] = self::getService();
932 $data = array_merge($data, self::createPermissionBlockForItem($item, false));
934 if (in_array($data['type'], ['Create', 'Update', 'Delete'])) {
935 $data['object'] = self::createNote($item);
936 } elseif ($data['type'] == 'Add') {
937 $data = self::createAddTag($item, $data);
938 } elseif ($data['type'] == 'Announce') {
939 $data = self::createAnnounce($item, $data);
940 } elseif ($data['type'] == 'Follow') {
941 $data['object'] = $item['parent-uri'];
942 } elseif ($data['type'] == 'Undo') {
943 $data['object'] = self::createActivityFromItem($item_id, true);
945 $data['diaspora:guid'] = $item['guid'];
946 if (!empty($item['signed_text'])) {
947 $data['diaspora:like'] = $item['signed_text'];
949 $data['object'] = $item['thr-parent'];
952 if (!empty($item['contact-uid'])) {
953 $uid = $item['contact-uid'];
958 $owner = User::getOwnerDataById($uid);
960 if (!$object_mode && !empty($owner)) {
961 return LDSignature::sign($data, $owner);
966 /// @todo Create "conversation" entry
970 * Creates a location entry for a given item array
974 * @return array with location array
976 private static function createLocation($item)
978 $location = ['type' => 'Place'];
980 if (!empty($item['location'])) {
981 $location['name'] = $item['location'];
986 if (empty($item['coord'])) {
987 $coord = Map::getCoordinates($item['location']);
989 $coords = explode(' ', $item['coord']);
990 if (count($coords) == 2) {
991 $coord = ['lat' => $coords[0], 'lon' => $coords[1]];
995 if (!empty($coord['lat']) && !empty($coord['lon'])) {
996 $location['latitude'] = $coord['lat'];
997 $location['longitude'] = $coord['lon'];
1004 * Returns a tag array for a given item array
1006 * @param array $item
1008 * @return array of tags
1009 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1011 private static function createTagList($item)
1015 $terms = Tag::getByURIId($item['uri-id'], [Tag::HASHTAG, Tag::MENTION, Tag::IMPLICIT_MENTION, Tag::EXCLUSIVE_MENTION]);
1016 foreach ($terms as $term) {
1017 if ($term['type'] == Tag::HASHTAG) {
1018 $url = DI::baseUrl() . '/search?tag=' . urlencode($term['term']);
1019 $tags[] = ['type' => 'Hashtag', 'href' => $url, 'name' => '#' . $term['term']];
1021 $contact = Contact::getDetailsByURL($term['url']);
1022 if (!empty($contact['addr'])) {
1023 $mention = '@' . $contact['addr'];
1025 $mention = '@' . $term['url'];
1028 $tags[] = ['type' => 'Mention', 'href' => $term['url'], 'name' => $mention];
1032 $announce = self::getAnnounceArray($item);
1033 // Mention the original author upon commented reshares
1034 if (!empty($announce['comment'])) {
1035 $tags[] = ['type' => 'Mention', 'href' => $announce['actor']['url'], 'name' => '@' . $announce['actor']['addr']];
1042 * Adds attachment data to the JSON document
1044 * @param array $item Data of the item that is to be posted
1045 * @param string $type Object type
1047 * @return array with attachment data
1048 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1050 private static function createAttachmentList($item, $type)
1054 // Currently deactivated, since it creates side effects on Mastodon and Pleroma.
1055 // It will be reactivated, once this cleared.
1057 $attach_data = BBCode::getAttachmentData($item['body']);
1058 if (!empty($attach_data['url'])) {
1059 $attachment = ['type' => 'Page',
1060 'mediaType' => 'text/html',
1061 'url' => $attach_data['url']];
1063 if (!empty($attach_data['title'])) {
1064 $attachment['name'] = $attach_data['title'];
1067 if (!empty($attach_data['description'])) {
1068 $attachment['summary'] = $attach_data['description'];
1071 if (!empty($attach_data['image'])) {
1072 $imgdata = Images::getInfoFromURLCached($attach_data['image']);
1074 $attachment['icon'] = ['type' => 'Image',
1075 'mediaType' => $imgdata['mime'],
1076 'width' => $imgdata[0],
1077 'height' => $imgdata[1],
1078 'url' => $attach_data['image']];
1082 $attachments[] = $attachment;
1085 $arr = explode('[/attach],', $item['attach']);
1087 foreach ($arr as $r) {
1089 $cnt = preg_match('|\[attach\]href=\"(.*?)\" length=\"(.*?)\" type=\"(.*?)\" title=\"(.*?)\"|', $r, $matches);
1091 $attributes = ['type' => 'Document',
1092 'mediaType' => $matches[3],
1093 'url' => $matches[1],
1096 if (trim($matches[4]) != '') {
1097 $attributes['name'] = trim($matches[4]);
1100 $attachments[] = $attributes;
1105 if ($type != 'Note') {
1106 return $attachments;
1109 // Simplify image codes
1110 $body = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '[img]$3[/img]', $item['body']);
1112 // Grab all pictures without alternative descriptions and create attachments out of them
1113 if (preg_match_all("/\[img\]([^\[\]]*)\[\/img\]/Usi", $body, $pictures)) {
1114 foreach ($pictures[1] as $picture) {
1115 $imgdata = Images::getInfoFromURLCached($picture);
1117 $attachments[] = ['type' => 'Document',
1118 'mediaType' => $imgdata['mime'],
1125 // Grab all pictures with alternative description and create attachments out of them
1126 if (preg_match_all("/\[img=([^\[\]]*)\]([^\[\]]*)\[\/img\]/Usi", $body, $pictures, PREG_SET_ORDER)) {
1127 foreach ($pictures as $picture) {
1128 $imgdata = Images::getInfoFromURLCached($picture[1]);
1130 $attachments[] = ['type' => 'Document',
1131 'mediaType' => $imgdata['mime'],
1132 'url' => $picture[1],
1133 'name' => $picture[2]];
1138 return $attachments;
1142 * Callback function to replace a Friendica style mention in a mention that is used on AP
1144 * @param array $match Matching values for the callback
1145 * @return string Replaced mention
1146 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1148 private static function mentionCallback($match)
1150 if (empty($match[1])) {
1154 $data = Contact::getDetailsByURL($match[1]);
1155 if (empty($data['nick'])) {
1159 return '@[url=' . $data['url'] . ']' . $data['nick'] . '[/url]';
1163 * Remove image elements since they are added as attachment
1165 * @param string $body
1167 * @return string with removed images
1169 private static function removePictures($body)
1171 // Simplify image codes
1172 $body = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '[img]$3[/img]', $body);
1173 $body = preg_replace("/\[img\=(.*?)\](.*?)\[\/img\]/ism", '[img]$1[/img]', $body);
1175 // Now remove local links
1176 $body = preg_replace_callback(
1177 '/\[url=([^\[\]]*)\]\[img\](.*)\[\/img\]\[\/url\]/Usi',
1179 // We remove the link when it is a link to a local photo page
1180 if (Photo::isLocalPage($match[1])) {
1183 // otherwise we just return the link
1184 return '[url]' . $match[1] . '[/url]';
1189 // Remove all pictures
1190 $body = preg_replace("/\[img\]([^\[\]]*)\[\/img\]/Usi", '', $body);
1196 * Fetches the "context" value for a givem item array from the "conversation" table
1198 * @param array $item
1200 * @return string with context url
1201 * @throws \Exception
1203 private static function fetchContextURLForItem($item)
1205 $conversation = DBA::selectFirst('conversation', ['conversation-href', 'conversation-uri'], ['item-uri' => $item['parent-uri']]);
1206 if (DBA::isResult($conversation) && !empty($conversation['conversation-href'])) {
1207 $context_uri = $conversation['conversation-href'];
1208 } elseif (DBA::isResult($conversation) && !empty($conversation['conversation-uri'])) {
1209 $context_uri = $conversation['conversation-uri'];
1211 $context_uri = $item['parent-uri'] . '#context';
1213 return $context_uri;
1217 * Returns if the post contains sensitive content ("nsfw")
1219 * @param integer $uri_id
1222 * @throws \Exception
1224 private static function isSensitive($uri_id)
1226 return DBA::exists('tag-view', ['uri-id' => $uri_id, 'name' => 'nsfw']);
1230 * Creates event data
1232 * @param array $item
1234 * @return array with the event data
1235 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1237 public static function createEvent($item)
1240 $event['name'] = $item['event-summary'];
1241 $event['content'] = BBCode::convert($item['event-desc'], false, 9);
1242 $event['startTime'] = DateTimeFormat::utc($item['event-start'] . '+00:00', DateTimeFormat::ATOM);
1244 if (!$item['event-nofinish']) {
1245 $event['endTime'] = DateTimeFormat::utc($item['event-finish'] . '+00:00', DateTimeFormat::ATOM);
1248 if (!empty($item['event-location'])) {
1249 $item['location'] = $item['event-location'];
1250 $event['location'] = self::createLocation($item);
1257 * Creates a note/article object array
1259 * @param array $item
1261 * @return array with the object data
1262 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1263 * @throws \ImagickException
1265 public static function createNote($item)
1271 if ($item['event-type'] == 'event') {
1273 } elseif (!empty($item['title'])) {
1279 if ($item['deleted']) {
1280 $type = 'Tombstone';
1284 $data['id'] = $item['uri'];
1285 $data['type'] = $type;
1287 if ($item['deleted']) {
1291 $data['summary'] = BBCode::toPlaintext(BBCode::getAbstract($item['body'], Protocol::ACTIVITYPUB));
1293 if ($item['uri'] != $item['thr-parent']) {
1294 $data['inReplyTo'] = $item['thr-parent'];
1296 $data['inReplyTo'] = null;
1299 $data['diaspora:guid'] = $item['guid'];
1300 $data['published'] = DateTimeFormat::utc($item['created'] . '+00:00', DateTimeFormat::ATOM);
1302 if ($item['created'] != $item['edited']) {
1303 $data['updated'] = DateTimeFormat::utc($item['edited'] . '+00:00', DateTimeFormat::ATOM);
1306 $data['url'] = $item['plink'];
1307 $data['attributedTo'] = $item['author-link'];
1308 $data['sensitive'] = self::isSensitive($item['uri-id']);
1309 $data['context'] = self::fetchContextURLForItem($item);
1311 if (!empty($item['title'])) {
1312 $data['name'] = BBCode::toPlaintext($item['title'], false);
1315 $permission_block = self::createPermissionBlockForItem($item, false);
1317 $body = $item['body'];
1319 if (empty($item['uid']) || !Feature::isEnabled($item['uid'], 'explicit_mentions')) {
1320 $body = self::prependMentions($body, $permission_block);
1323 if ($type == 'Note') {
1324 $body = self::removePictures($body);
1325 } elseif (($type == 'Article') && empty($data['summary'])) {
1326 $data['summary'] = BBCode::toPlaintext(Plaintext::shorten(self::removePictures($body), 1000));
1329 if ($type == 'Event') {
1330 $data = array_merge($data, self::createEvent($item));
1332 $regexp = "/[@!]\[url\=([^\[\]]*)\].*?\[\/url\]/ism";
1333 $body = preg_replace_callback($regexp, ['self', 'mentionCallback'], $body);
1335 $data['content'] = BBCode::convert($body, false, 9);
1338 // The regular "content" field does contain a minimized HTML. This is done since systems like
1339 // Mastodon has got problems with - for example - embedded pictures.
1340 // The contentMap does contain the unmodified HTML.
1341 $language = self::getLanguage($item);
1342 if (!empty($language)) {
1343 $regexp = "/[@!]\[url\=([^\[\]]*)\].*?\[\/url\]/ism";
1344 $richbody = preg_replace_callback($regexp, ['self', 'mentionCallback'], $item['body']);
1345 $richbody = BBCode::removeAttachment($richbody);
1347 $data['contentMap'][$language] = BBCode::convert($richbody, false);
1350 $data['source'] = ['content' => $item['body'], 'mediaType' => "text/bbcode"];
1352 if (!empty($item['signed_text']) && ($item['uri'] != $item['thr-parent'])) {
1353 $data['diaspora:comment'] = $item['signed_text'];
1356 $data['attachment'] = self::createAttachmentList($item, $type);
1357 $data['tag'] = self::createTagList($item);
1359 if (empty($data['location']) && (!empty($item['coord']) || !empty($item['location']))) {
1360 $data['location'] = self::createLocation($item);
1363 if (!empty($item['app'])) {
1364 $data['generator'] = ['type' => 'Application', 'name' => $item['app']];
1367 $data = array_merge($data, $permission_block);
1373 * Fetches the language from the post, the user or the system.
1375 * @param array $item
1377 * @return string language string
1379 private static function getLanguage(array $item)
1381 // Try to fetch the language from the post itself
1382 if (!empty($item['language'])) {
1383 $languages = array_keys(json_decode($item['language'], true));
1384 if (!empty($languages[0])) {
1385 return $languages[0];
1389 // Otherwise use the user's language
1390 if (!empty($item['uid'])) {
1391 $user = DBA::selectFirst('user', ['language'], ['uid' => $item['uid']]);
1392 if (!empty($user['language'])) {
1393 return $user['language'];
1397 // And finally just use the system language
1398 return DI::config()->get('system', 'language');
1402 * Creates an an "add tag" entry
1404 * @param array $item
1405 * @param array $data activity data
1407 * @return array with activity data for adding tags
1408 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1409 * @throws \ImagickException
1411 private static function createAddTag($item, $data)
1413 $object = XML::parseString($item['object']);
1414 $target = XML::parseString($item["target"]);
1416 $data['diaspora:guid'] = $item['guid'];
1417 $data['actor'] = $item['author-link'];
1418 $data['target'] = (string)$target->id;
1419 $data['summary'] = BBCode::toPlaintext($item['body']);
1420 $data['object'] = ['id' => (string)$object->id, 'type' => 'tag', 'name' => (string)$object->title, 'content' => (string)$object->content];
1426 * Creates an announce object entry
1428 * @param array $item
1429 * @param array $data activity data
1431 * @return array with activity data
1432 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1433 * @throws \ImagickException
1435 private static function createAnnounce($item, $data)
1437 $orig_body = $item['body'];
1438 $announce = self::getAnnounceArray($item);
1439 if (empty($announce)) {
1440 $data['type'] = 'Create';
1441 $data['object'] = self::createNote($item);
1445 if (empty($announce['comment'])) {
1446 // Pure announce, without a quote
1447 $data['type'] = 'Announce';
1448 $data['object'] = $announce['object']['uri'];
1453 $data['type'] = 'Create';
1454 $item['body'] = $announce['comment'] . "\n" . $announce['object']['plink'];
1455 $data['object'] = self::createNote($item);
1457 /// @todo Finally descide how to implement this in AP. This is a possible way:
1458 $data['object']['attachment'][] = self::createNote($announce['object']);
1460 $data['object']['source']['content'] = $orig_body;
1465 * Return announce related data if the item is an annunce
1467 * @param array $item
1471 public static function getAnnounceArray($item)
1473 $reshared = Item::getShareArray($item);
1474 if (empty($reshared['guid'])) {
1478 $reshared_item = Item::selectFirst([], ['guid' => $reshared['guid']]);
1479 if (!DBA::isResult($reshared_item)) {
1483 if (!in_array($reshared_item['network'], [Protocol::ACTIVITYPUB, Protocol::DFRN])) {
1487 $profile = APContact::getByURL($reshared_item['author-link'], false);
1488 if (empty($profile)) {
1492 return ['object' => $reshared_item, 'actor' => $profile, 'comment' => $reshared['comment']];
1496 * Checks if the provided item array is an announce
1498 * @param array $item
1502 public static function isAnnounce($item)
1504 $announce = self::getAnnounceArray($item);
1505 if (empty($announce)) {
1509 return empty($announce['comment']);
1513 * Creates an activity id for a given contact id
1515 * @param integer $cid Contact ID of target
1517 * @return bool|string activity id
1519 public static function activityIDFromContact($cid)
1521 $contact = DBA::selectFirst('contact', ['uid', 'id', 'created'], ['id' => $cid]);
1522 if (!DBA::isResult($contact)) {
1526 $hash = hash('ripemd128', $contact['uid'].'-'.$contact['id'].'-'.$contact['created']);
1527 $uuid = substr($hash, 0, 8). '-' . substr($hash, 8, 4) . '-' . substr($hash, 12, 4) . '-' . substr($hash, 16, 4) . '-' . substr($hash, 20, 12);
1528 return DI::baseUrl() . '/activity/' . $uuid;
1532 * Transmits a contact suggestion to a given inbox
1534 * @param integer $uid User ID
1535 * @param string $inbox Target inbox
1536 * @param integer $suggestion_id Suggestion ID
1538 * @return boolean was the transmission successful?
1539 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1541 public static function sendContactSuggestion($uid, $inbox, $suggestion_id)
1543 $owner = User::getOwnerDataById($uid);
1545 $suggestion = DI::fsuggest()->getById($suggestion_id);
1547 $data = ['@context' => ActivityPub::CONTEXT,
1548 'id' => DI::baseUrl() . '/activity/' . System::createGUID(),
1549 'type' => 'Announce',
1550 'actor' => $owner['url'],
1551 'object' => $suggestion->url,
1552 'content' => $suggestion->note,
1553 'instrument' => self::getService(),
1554 'to' => [ActivityPub::PUBLIC_COLLECTION],
1557 $signed = LDSignature::sign($data, $owner);
1559 Logger::log('Deliver profile deletion for user ' . $uid . ' to ' . $inbox . ' via ActivityPub', Logger::DEBUG);
1560 return HTTPSignature::transmit($signed, $inbox, $uid);
1564 * Transmits a profile relocation to a given inbox
1566 * @param integer $uid User ID
1567 * @param string $inbox Target inbox
1569 * @return boolean was the transmission successful?
1570 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1572 public static function sendProfileRelocation($uid, $inbox)
1574 $owner = User::getOwnerDataById($uid);
1576 $data = ['@context' => ActivityPub::CONTEXT,
1577 'id' => DI::baseUrl() . '/activity/' . System::createGUID(),
1578 'type' => 'dfrn:relocate',
1579 'actor' => $owner['url'],
1580 'object' => $owner['url'],
1581 'published' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
1582 'instrument' => self::getService(),
1583 'to' => [ActivityPub::PUBLIC_COLLECTION],
1586 $signed = LDSignature::sign($data, $owner);
1588 Logger::log('Deliver profile relocation for user ' . $uid . ' to ' . $inbox . ' via ActivityPub', Logger::DEBUG);
1589 return HTTPSignature::transmit($signed, $inbox, $uid);
1593 * Transmits a profile deletion to a given inbox
1595 * @param integer $uid User ID
1596 * @param string $inbox Target inbox
1598 * @return boolean was the transmission successful?
1599 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1601 public static function sendProfileDeletion($uid, $inbox)
1603 $owner = User::getOwnerDataById($uid);
1605 if (empty($owner)) {
1606 Logger::error('No owner data found, the deletion message cannot be processed.', ['user' => $uid]);
1610 if (empty($owner['uprvkey'])) {
1611 Logger::error('No private key for owner found, the deletion message cannot be processed.', ['user' => $uid]);
1615 $data = ['@context' => ActivityPub::CONTEXT,
1616 'id' => DI::baseUrl() . '/activity/' . System::createGUID(),
1618 'actor' => $owner['url'],
1619 'object' => $owner['url'],
1620 'published' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
1621 'instrument' => self::getService(),
1622 'to' => [ActivityPub::PUBLIC_COLLECTION],
1625 $signed = LDSignature::sign($data, $owner);
1627 Logger::log('Deliver profile deletion for user ' . $uid . ' to ' . $inbox . ' via ActivityPub', Logger::DEBUG);
1628 return HTTPSignature::transmit($signed, $inbox, $uid);
1632 * Transmits a profile change to a given inbox
1634 * @param integer $uid User ID
1635 * @param string $inbox Target inbox
1637 * @return boolean was the transmission successful?
1638 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1639 * @throws \ImagickException
1641 public static function sendProfileUpdate($uid, $inbox)
1643 $owner = User::getOwnerDataById($uid);
1644 $profile = APContact::getByURL($owner['url']);
1646 $data = ['@context' => ActivityPub::CONTEXT,
1647 'id' => DI::baseUrl() . '/activity/' . System::createGUID(),
1649 'actor' => $owner['url'],
1650 'object' => self::getProfile($uid),
1651 'published' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
1652 'instrument' => self::getService(),
1653 'to' => [$profile['followers']],
1656 $signed = LDSignature::sign($data, $owner);
1658 Logger::log('Deliver profile update for user ' . $uid . ' to ' . $inbox . ' via ActivityPub', Logger::DEBUG);
1659 return HTTPSignature::transmit($signed, $inbox, $uid);
1663 * Transmits a given activity to a target
1665 * @param string $activity Type name
1666 * @param string $target Target profile
1667 * @param integer $uid User ID
1669 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1670 * @throws \ImagickException
1671 * @throws \Exception
1673 public static function sendActivity($activity, $target, $uid, $id = '')
1675 $profile = APContact::getByURL($target);
1676 if (empty($profile['inbox'])) {
1677 Logger::warning('No inbox found for target', ['target' => $target, 'profile' => $profile]);
1681 $owner = User::getOwnerDataById($uid);
1684 $id = DI::baseUrl() . '/activity/' . System::createGUID();
1687 $data = ['@context' => ActivityPub::CONTEXT,
1689 'type' => $activity,
1690 'actor' => $owner['url'],
1691 'object' => $profile['url'],
1692 'instrument' => self::getService(),
1693 'to' => [$profile['url']]];
1695 Logger::log('Sending activity ' . $activity . ' to ' . $target . ' for user ' . $uid, Logger::DEBUG);
1697 $signed = LDSignature::sign($data, $owner);
1698 return HTTPSignature::transmit($signed, $profile['inbox'], $uid);
1702 * Transmits a "follow object" activity to a target
1703 * This is a preparation for sending automated "follow" requests when receiving "Announce" messages
1705 * @param string $object Object URL
1706 * @param string $target Target profile
1707 * @param integer $uid User ID
1709 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1710 * @throws \ImagickException
1711 * @throws \Exception
1713 public static function sendFollowObject($object, $target, $uid = 0)
1715 $profile = APContact::getByURL($target);
1716 if (empty($profile['inbox'])) {
1717 Logger::warning('No inbox found for target', ['target' => $target, 'profile' => $profile]);
1722 // Fetch the list of administrators
1723 $admin_mail = explode(',', str_replace(' ', '', DI::config()->get('config', 'admin_email')));
1725 // We need to use some user as a sender. It doesn't care who it will send. We will use an administrator account.
1726 $condition = ['verified' => true, 'blocked' => false, 'account_removed' => false, 'account_expired' => false, 'email' => $admin_mail];
1727 $first_user = DBA::selectFirst('user', ['uid'], $condition);
1728 $uid = $first_user['uid'];
1731 $condition = ['verb' => Activity::FOLLOW, 'uid' => 0, 'parent-uri' => $object,
1732 'author-id' => Contact::getPublicIdByUserId($uid)];
1733 if (Item::exists($condition)) {
1734 Logger::log('Follow for ' . $object . ' for user ' . $uid . ' does already exist.', Logger::DEBUG);
1738 $owner = User::getOwnerDataById($uid);
1740 $data = ['@context' => ActivityPub::CONTEXT,
1741 'id' => DI::baseUrl() . '/activity/' . System::createGUID(),
1743 'actor' => $owner['url'],
1744 'object' => $object,
1745 'instrument' => self::getService(),
1746 'to' => [$profile['url']]];
1748 Logger::log('Sending follow ' . $object . ' to ' . $target . ' for user ' . $uid, Logger::DEBUG);
1750 $signed = LDSignature::sign($data, $owner);
1751 return HTTPSignature::transmit($signed, $profile['inbox'], $uid);
1755 * Transmit a message that the contact request had been accepted
1757 * @param string $target Target profile
1759 * @param integer $uid User ID
1760 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1761 * @throws \ImagickException
1763 public static function sendContactAccept($target, $id, $uid)
1765 $profile = APContact::getByURL($target);
1766 if (empty($profile['inbox'])) {
1767 Logger::warning('No inbox found for target', ['target' => $target, 'profile' => $profile]);
1771 $owner = User::getOwnerDataById($uid);
1772 $data = ['@context' => ActivityPub::CONTEXT,
1773 'id' => DI::baseUrl() . '/activity/' . System::createGUID(),
1775 'actor' => $owner['url'],
1777 'id' => (string)$id,
1779 'actor' => $profile['url'],
1780 'object' => $owner['url']
1782 'instrument' => self::getService(),
1783 'to' => [$profile['url']]];
1785 Logger::debug('Sending accept to ' . $target . ' for user ' . $uid . ' with id ' . $id);
1787 $signed = LDSignature::sign($data, $owner);
1788 HTTPSignature::transmit($signed, $profile['inbox'], $uid);
1792 * Reject a contact request or terminates the contact relation
1794 * @param string $target Target profile
1796 * @param integer $uid User ID
1797 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1798 * @throws \ImagickException
1800 public static function sendContactReject($target, $id, $uid)
1802 $profile = APContact::getByURL($target);
1803 if (empty($profile['inbox'])) {
1804 Logger::warning('No inbox found for target', ['target' => $target, 'profile' => $profile]);
1808 $owner = User::getOwnerDataById($uid);
1809 $data = ['@context' => ActivityPub::CONTEXT,
1810 'id' => DI::baseUrl() . '/activity/' . System::createGUID(),
1812 'actor' => $owner['url'],
1814 'id' => (string)$id,
1816 'actor' => $profile['url'],
1817 'object' => $owner['url']
1819 'instrument' => self::getService(),
1820 'to' => [$profile['url']]];
1822 Logger::debug('Sending reject to ' . $target . ' for user ' . $uid . ' with id ' . $id);
1824 $signed = LDSignature::sign($data, $owner);
1825 HTTPSignature::transmit($signed, $profile['inbox'], $uid);
1829 * Transmits a message that we don't want to follow this contact anymore
1831 * @param string $target Target profile
1832 * @param integer $uid User ID
1833 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1834 * @throws \ImagickException
1835 * @throws \Exception
1837 public static function sendContactUndo($target, $cid, $uid)
1839 $profile = APContact::getByURL($target);
1840 if (empty($profile['inbox'])) {
1841 Logger::warning('No inbox found for target', ['target' => $target, 'profile' => $profile]);
1845 $object_id = self::activityIDFromContact($cid);
1846 if (empty($object_id)) {
1850 $id = DI::baseUrl() . '/activity/' . System::createGUID();
1852 $owner = User::getOwnerDataById($uid);
1853 $data = ['@context' => ActivityPub::CONTEXT,
1856 'actor' => $owner['url'],
1857 'object' => ['id' => $object_id, 'type' => 'Follow',
1858 'actor' => $owner['url'],
1859 'object' => $profile['url']],
1860 'instrument' => self::getService(),
1861 'to' => [$profile['url']]];
1863 Logger::log('Sending undo to ' . $target . ' for user ' . $uid . ' with id ' . $id, Logger::DEBUG);
1865 $signed = LDSignature::sign($data, $owner);
1866 HTTPSignature::transmit($signed, $profile['inbox'], $uid);
1869 private static function prependMentions($body, array $permission_block)
1871 if (DI::config()->get('system', 'disable_implicit_mentions')) {
1877 foreach ($permission_block['to'] as $profile_url) {
1878 $profile = Contact::getDetailsByURL($profile_url);
1879 if (!empty($profile['addr'])
1880 && $profile['contact-type'] != Contact::TYPE_COMMUNITY
1881 && !strstr($body, $profile['addr'])
1882 && !strstr($body, $profile_url)
1884 $mentions[] = '@[url=' . $profile_url . ']' . $profile['nick'] . '[/url]';
1888 $mentions[] = $body;
1890 return implode(' ', $mentions);