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\Tag;
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'];
101 $data['next'] = DI::baseUrl() . '/followers/' . $owner['nickname'] . '?page=' . ($page + 1);
104 $data['partOf'] = DI::baseUrl() . '/followers/' . $owner['nickname'];
106 $data['orderedItems'] = $list;
113 * Create list of following contacts
115 * @param array $owner Owner array
116 * @param integer $page Page numbe
118 * @return array of following contacts
119 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
121 public static function getFollowing($owner, $page = null)
123 $condition = ['rel' => [Contact::SHARING, Contact::FRIEND], 'network' => Protocol::FEDERATED, 'uid' => $owner['uid'],
124 'self' => false, 'deleted' => false, 'hidden' => false, 'archive' => false, 'pending' => false];
125 $count = DBA::count('contact', $condition);
127 $data = ['@context' => ActivityPub::CONTEXT];
128 $data['id'] = DI::baseUrl() . '/following/' . $owner['nickname'];
129 $data['type'] = 'OrderedCollection';
130 $data['totalItems'] = $count;
132 // When we hide our friends we will only show the pure number but don't allow more.
133 $profile = Profile::getByUID($owner['uid']);
134 if (!empty($profile['hide-friends'])) {
139 $data['first'] = DI::baseUrl() . '/following/' . $owner['nickname'] . '?page=1';
141 $data['type'] = 'OrderedCollectionPage';
144 $contacts = DBA::select('contact', ['url'], $condition, ['limit' => [($page - 1) * 100, 100]]);
145 while ($contact = DBA::fetch($contacts)) {
146 $list[] = $contact['url'];
150 $data['next'] = DI::baseUrl() . '/following/' . $owner['nickname'] . '?page=' . ($page + 1);
153 $data['partOf'] = DI::baseUrl() . '/following/' . $owner['nickname'];
155 $data['orderedItems'] = $list;
162 * Public posts for the given owner
164 * @param array $owner Owner array
165 * @param integer $page Page numbe
167 * @return array of posts
168 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
169 * @throws \ImagickException
171 public static function getOutbox($owner, $page = null)
173 $public_contact = Contact::getIdForURL($owner['url'], 0, true);
175 $condition = ['uid' => 0, 'contact-id' => $public_contact, 'author-id' => $public_contact,
176 'private' => [Item::PUBLIC, Item::UNLISTED], 'gravity' => [GRAVITY_PARENT, GRAVITY_COMMENT],
177 'deleted' => false, 'visible' => true, 'moderated' => false];
178 $count = DBA::count('item', $condition);
180 $data = ['@context' => ActivityPub::CONTEXT];
181 $data['id'] = DI::baseUrl() . '/outbox/' . $owner['nickname'];
182 $data['type'] = 'OrderedCollection';
183 $data['totalItems'] = $count;
186 $data['first'] = DI::baseUrl() . '/outbox/' . $owner['nickname'] . '?page=1';
188 $data['type'] = 'OrderedCollectionPage';
191 $condition['parent-network'] = Protocol::NATIVE_SUPPORT;
193 $items = Item::select(['id'], $condition, ['limit' => [($page - 1) * 20, 20], 'order' => ['created' => true]]);
194 while ($item = Item::fetch($items)) {
195 $activity = self::createActivityFromItem($item['id'], true);
196 $activity['type'] = $activity['type'] == 'Update' ? 'Create' : $activity['type'];
198 // Only list "Create" activity objects here, no reshares
199 if (!empty($activity['object']) && ($activity['type'] == 'Create')) {
200 $list[] = $activity['object'];
205 $data['next'] = DI::baseUrl() . '/outbox/' . $owner['nickname'] . '?page=' . ($page + 1);
208 $data['partOf'] = DI::baseUrl() . '/outbox/' . $owner['nickname'];
210 $data['orderedItems'] = $list;
217 * Return the service array containing information the used software and it's url
219 * @return array with service data
221 private static function getService()
223 return ['type' => 'Service',
224 'name' => FRIENDICA_PLATFORM . " '" . FRIENDICA_CODENAME . "' " . FRIENDICA_VERSION . '-' . DB_UPDATE_VERSION,
225 'url' => DI::baseUrl()->get()];
229 * Return the ActivityPub profile of the given user
231 * @param integer $uid User ID
232 * @return array with profile data
233 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
235 public static function getProfile($uid)
237 $condition = ['uid' => $uid, 'blocked' => false, 'account_expired' => false,
238 'account_removed' => false, 'verified' => true];
239 $fields = ['guid', 'nickname', 'pubkey', 'account-type', 'page-flags'];
240 $user = DBA::selectFirst('user', $fields, $condition);
241 if (!DBA::isResult($user)) {
245 $fields = ['locality', 'region', 'country-name'];
246 $profile = DBA::selectFirst('profile', $fields, ['uid' => $uid]);
247 if (!DBA::isResult($profile)) {
251 $fields = ['name', 'url', 'location', 'about', 'avatar', 'photo'];
252 $contact = DBA::selectFirst('contact', $fields, ['uid' => $uid, 'self' => true]);
253 if (!DBA::isResult($contact)) {
257 $data = ['@context' => ActivityPub::CONTEXT];
258 $data['id'] = $contact['url'];
259 $data['diaspora:guid'] = $user['guid'];
260 $data['type'] = ActivityPub::ACCOUNT_TYPES[$user['account-type']];
261 $data['following'] = DI::baseUrl() . '/following/' . $user['nickname'];
262 $data['followers'] = DI::baseUrl() . '/followers/' . $user['nickname'];
263 $data['inbox'] = DI::baseUrl() . '/inbox/' . $user['nickname'];
264 $data['outbox'] = DI::baseUrl() . '/outbox/' . $user['nickname'];
265 $data['preferredUsername'] = $user['nickname'];
266 $data['name'] = $contact['name'];
267 $data['vcard:hasAddress'] = ['@type' => 'vcard:Home', 'vcard:country-name' => $profile['country-name'],
268 'vcard:region' => $profile['region'], 'vcard:locality' => $profile['locality']];
269 $data['summary'] = BBCode::convert($contact['about'], false);
270 $data['url'] = $contact['url'];
271 $data['manuallyApprovesFollowers'] = in_array($user['page-flags'], [User::PAGE_FLAGS_NORMAL, User::PAGE_FLAGS_PRVGROUP]);
272 $data['publicKey'] = ['id' => $contact['url'] . '#main-key',
273 'owner' => $contact['url'],
274 'publicKeyPem' => $user['pubkey']];
275 $data['endpoints'] = ['sharedInbox' => DI::baseUrl() . '/inbox'];
276 $data['icon'] = ['type' => 'Image',
277 'url' => $contact['photo']];
279 $data['generator'] = self::getService();
281 // tags: https://kitty.town/@inmysocks/100656097926961126.json
286 * @param string $username
288 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
290 public static function getDeletedUser($username)
293 '@context' => ActivityPub::CONTEXT,
294 'id' => DI::baseUrl() . '/profile/' . $username,
295 'type' => 'Tombstone',
296 'published' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
297 'updated' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
298 'deleted' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
303 * Returns an array with permissions of a given item array
307 * @return array with permissions
308 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
309 * @throws \ImagickException
311 private static function fetchPermissionBlockFromConversation($item)
313 if (empty($item['thr-parent'])) {
317 $condition = ['item-uri' => $item['thr-parent'], 'protocol' => Conversation::PARCEL_ACTIVITYPUB];
318 $conversation = DBA::selectFirst('conversation', ['source'], $condition);
319 if (!DBA::isResult($conversation)) {
323 $activity = json_decode($conversation['source'], true);
325 $actor = JsonLD::fetchElement($activity, 'actor', 'id');
326 $profile = APContact::getByURL($actor);
328 $item_profile = APContact::getByURL($item['author-link']);
329 $exclude[] = $item['author-link'];
331 if ($item['gravity'] == GRAVITY_PARENT) {
332 $exclude[] = $item['owner-link'];
335 $permissions['to'][] = $actor;
337 foreach (['to', 'cc', 'bto', 'bcc'] as $element) {
338 if (empty($activity[$element])) {
341 if (is_string($activity[$element])) {
342 $activity[$element] = [$activity[$element]];
345 foreach ($activity[$element] as $receiver) {
346 if (empty($receiver)) {
350 if (!empty($profile['followers']) && $receiver == $profile['followers'] && !empty($item_profile['followers'])) {
351 $permissions[$element][] = $item_profile['followers'];
352 } elseif (!in_array($receiver, $exclude)) {
353 $permissions[$element][] = $receiver;
361 * Creates an array of permissions from an item thread
363 * @param array $item Item array
364 * @param boolean $blindcopy addressing via "bcc" or "cc"?
365 * @param integer $last_id Last item id for adding receivers
366 * @param boolean $forum_mode "true" means that we are sending content to a forum
368 * @return array with permission data
369 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
370 * @throws \ImagickException
372 private static function createPermissionBlockForItem($item, $blindcopy, $last_id = 0, $forum_mode = false)
375 $last_id = $item['id'];
380 // Check if we should always deliver our stuff via BCC
381 if (!empty($item['uid'])) {
382 $profile = Profile::getByUID($item['uid']);
383 if (!empty($profile)) {
384 $always_bcc = $profile['hide-friends'];
388 if (DI::config()->get('system', 'ap_always_bcc')) {
392 if (self::isAnnounce($item) || DI::config()->get('debug', 'total_ap_delivery')) {
393 // Will be activated in a later step
394 $networks = Protocol::FEDERATED;
396 // For now only send to these contacts:
397 $networks = [Protocol::ACTIVITYPUB, Protocol::OSTATUS];
400 $data = ['to' => [], 'cc' => [], 'bcc' => []];
402 if ($item['gravity'] == GRAVITY_PARENT) {
403 $actor_profile = APContact::getByURL($item['owner-link']);
405 $actor_profile = APContact::getByURL($item['author-link']);
408 $terms = Tag::ArrayFromURIId($item['uri-id'], [Tag::MENTION, Tag::IMPLICIT_MENTION, Tag::EXCLUSIVE_MENTION]);
410 if ($item['private'] != Item::PRIVATE) {
411 // Directly mention the original author upon a quoted reshare.
412 // Else just ensure that the original author receives the reshare.
413 $announce = self::getAnnounceArray($item);
414 if (!empty($announce['comment'])) {
415 $data['to'][] = $announce['actor']['url'];
416 } elseif (!empty($announce)) {
417 $data['cc'][] = $announce['actor']['url'];
420 $data = array_merge($data, self::fetchPermissionBlockFromConversation($item));
422 // Check if the item is completely public or unlisted
423 if ($item['private'] == Item::PUBLIC) {
424 $data['to'][] = ActivityPub::PUBLIC_COLLECTION;
426 $data['cc'][] = ActivityPub::PUBLIC_COLLECTION;
429 foreach ($terms as $term) {
430 $profile = APContact::getByURL($term['url'], false);
431 if (!empty($profile)) {
432 $data['to'][] = $profile['url'];
436 $receiver_list = Item::enumeratePermissions($item, true);
438 foreach ($terms as $term) {
439 $cid = Contact::getIdForURL($term['url'], $item['uid']);
440 if (!empty($cid) && in_array($cid, $receiver_list)) {
441 $contact = DBA::selectFirst('contact', ['url', 'network', 'protocol'], ['id' => $cid]);
442 if (!DBA::isResult($contact) || (!in_array($contact['network'], $networks) && ($contact['protocol'] != Protocol::ACTIVITYPUB))) {
446 if (!empty($profile = APContact::getByURL($contact['url'], false))) {
447 $data['to'][] = $profile['url'];
452 foreach ($receiver_list as $receiver) {
453 $contact = DBA::selectFirst('contact', ['url', 'hidden', 'network', 'protocol'], ['id' => $receiver]);
454 if (!DBA::isResult($contact) || (!in_array($contact['network'], $networks) && ($contact['protocol'] != Protocol::ACTIVITYPUB))) {
458 if (!empty($profile = APContact::getByURL($contact['url'], false))) {
459 if ($contact['hidden'] || $always_bcc) {
460 $data['bcc'][] = $profile['url'];
462 $data['cc'][] = $profile['url'];
468 if (!empty($item['parent'])) {
469 $parents = Item::select(['id', 'author-link', 'owner-link', 'gravity', 'uri'], ['parent' => $item['parent']]);
470 while ($parent = Item::fetch($parents)) {
471 if ($parent['gravity'] == GRAVITY_PARENT) {
472 $profile = APContact::getByURL($parent['owner-link'], false);
473 if (!empty($profile)) {
474 if ($item['gravity'] != GRAVITY_PARENT) {
475 // Comments to forums are directed to the forum
476 // But comments to forums aren't directed to the followers collection
477 if ($profile['type'] == 'Group') {
478 $data['to'][] = $profile['url'];
480 $data['cc'][] = $profile['url'];
481 if (($item['private'] != Item::PRIVATE) && !empty($actor_profile['followers'])) {
482 $data['cc'][] = $actor_profile['followers'];
486 // Public thread parent post always are directed to the followers
487 if (($item['private'] != Item::PRIVATE) && !$forum_mode) {
488 $data['cc'][] = $actor_profile['followers'];
494 // Don't include data from future posts
495 if ($parent['id'] >= $last_id) {
499 $profile = APContact::getByURL($parent['author-link'], false);
500 if (!empty($profile)) {
501 if (($profile['type'] == 'Group') || ($parent['uri'] == $item['thr-parent'])) {
502 $data['to'][] = $profile['url'];
504 $data['cc'][] = $profile['url'];
508 DBA::close($parents);
511 $data['to'] = array_unique($data['to']);
512 $data['cc'] = array_unique($data['cc']);
513 $data['bcc'] = array_unique($data['bcc']);
515 if (($key = array_search($item['author-link'], $data['to'])) !== false) {
516 unset($data['to'][$key]);
519 if (($key = array_search($item['author-link'], $data['cc'])) !== false) {
520 unset($data['cc'][$key]);
523 if (($key = array_search($item['author-link'], $data['bcc'])) !== false) {
524 unset($data['bcc'][$key]);
527 foreach ($data['to'] as $to) {
528 if (($key = array_search($to, $data['cc'])) !== false) {
529 unset($data['cc'][$key]);
532 if (($key = array_search($to, $data['bcc'])) !== false) {
533 unset($data['bcc'][$key]);
537 foreach ($data['cc'] as $cc) {
538 if (($key = array_search($cc, $data['bcc'])) !== false) {
539 unset($data['bcc'][$key]);
543 $receivers = ['to' => array_values($data['to']), 'cc' => array_values($data['cc']), 'bcc' => array_values($data['bcc'])];
546 unset($receivers['bcc']);
553 * Check if an inbox is archived
555 * @param string $url Inbox url
557 * @return boolean "true" if inbox is archived
559 private static function archivedInbox($url)
561 return DBA::exists('inbox-status', ['url' => $url, 'archive' => true]);
565 * Fetches a list of inboxes of followers of a given user
567 * @param integer $uid User ID
568 * @param boolean $personal fetch personal inboxes
570 * @return array of follower inboxes
571 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
572 * @throws \ImagickException
574 public static function fetchTargetInboxesforUser($uid, $personal = false)
578 if (DI::config()->get('debug', 'total_ap_delivery')) {
579 // Will be activated in a later step
580 $networks = Protocol::FEDERATED;
582 // For now only send to these contacts:
583 $networks = [Protocol::ACTIVITYPUB, Protocol::OSTATUS];
586 $condition = ['uid' => $uid, 'archive' => false, 'pending' => false];
589 $condition['rel'] = [Contact::FOLLOWER, Contact::FRIEND];
592 $contacts = DBA::select('contact', ['url', 'network', 'protocol'], $condition);
593 while ($contact = DBA::fetch($contacts)) {
594 if (Contact::isLocal($contact['url'])) {
598 if (!in_array($contact['network'], $networks) && ($contact['protocol'] != Protocol::ACTIVITYPUB)) {
602 if (Network::isUrlBlocked($contact['url'])) {
606 $profile = APContact::getByURL($contact['url'], false);
607 if (!empty($profile)) {
608 if (empty($profile['sharedinbox']) || $personal) {
609 $target = $profile['inbox'];
611 $target = $profile['sharedinbox'];
613 if (!self::archivedInbox($target)) {
614 $inboxes[$target] = $target;
618 DBA::close($contacts);
624 * Fetches an array of inboxes for the given item and user
626 * @param array $item Item array
627 * @param integer $uid User ID
628 * @param boolean $personal fetch personal inboxes
629 * @param integer $last_id Last item id for adding receivers
630 * @param boolean $forum_mode "true" means that we are sending content to a forum
631 * @return array with inboxes
632 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
633 * @throws \ImagickException
635 public static function fetchTargetInboxes($item, $uid, $personal = false, $last_id = 0, $forum_mode = false)
637 $permissions = self::createPermissionBlockForItem($item, true, $last_id, $forum_mode);
638 if (empty($permissions)) {
644 if ($item['gravity'] == GRAVITY_ACTIVITY) {
645 $item_profile = APContact::getByURL($item['author-link'], false);
647 $item_profile = APContact::getByURL($item['owner-link'], false);
650 foreach (['to', 'cc', 'bto', 'bcc'] as $element) {
651 if (empty($permissions[$element])) {
655 $blindcopy = in_array($element, ['bto', 'bcc']);
657 foreach ($permissions[$element] as $receiver) {
658 if (empty($receiver) || Network::isUrlBlocked($receiver)) {
662 if ($receiver == $item_profile['followers']) {
663 $inboxes = array_merge($inboxes, self::fetchTargetInboxesforUser($uid, $personal));
665 if (Contact::isLocal($receiver)) {
669 $profile = APContact::getByURL($receiver, false);
670 if (!empty($profile)) {
671 if (empty($profile['sharedinbox']) || $personal || $blindcopy) {
672 $target = $profile['inbox'];
674 $target = $profile['sharedinbox'];
676 if (!self::archivedInbox($target)) {
677 $inboxes[$target] = $target;
688 * Creates an array in the structure of the item table for a given mail id
690 * @param integer $mail_id
695 public static function ItemArrayFromMail($mail_id)
697 $mail = DBA::selectFirst('mail', [], ['id' => $mail_id]);
698 if (!DBA::isResult($mail)) {
702 $reply = DBA::selectFirst('mail', ['uri'], ['parent-uri' => $mail['parent-uri'], 'reply' => false]);
704 // Making the post more compatible for Mastodon by:
705 // - Making it a note and not an article (no title)
706 // - Moving the title into the "summary" field that is used as a "content warning"
707 $mail['body'] = '[abstract]' . $mail['title'] . "[/abstract]\n" . $mail['body'];
710 $mail['author-link'] = $mail['owner-link'] = $mail['from-url'];
711 $mail['allow_cid'] = '<'.$mail['contact-id'].'>';
712 $mail['allow_gid'] = '';
713 $mail['deny_cid'] = '';
714 $mail['deny_gid'] = '';
715 $mail['private'] = true;
716 $mail['deleted'] = false;
717 $mail['edited'] = $mail['created'];
718 $mail['plink'] = $mail['uri'];
719 $mail['thr-parent'] = $reply['uri'];
720 $mail['gravity'] = ($mail['reply'] ? GRAVITY_COMMENT: GRAVITY_PARENT);
722 $mail['event-type'] = '';
723 $mail['attach'] = '';
731 * Creates an activity array for a given mail id
733 * @param integer $mail_id
734 * @param boolean $object_mode Is the activity item is used inside another object?
736 * @return array of activity
739 public static function createActivityFromMail($mail_id, $object_mode = false)
741 $mail = self::ItemArrayFromMail($mail_id);
742 $object = self::createNote($mail);
745 $data = ['@context' => ActivityPub::CONTEXT];
750 $data['id'] = $mail['uri'] . '#Create';
751 $data['type'] = 'Create';
752 $data['actor'] = $mail['author-link'];
753 $data['published'] = DateTimeFormat::utc($mail['created'] . '+00:00', DateTimeFormat::ATOM);
754 $data['instrument'] = self::getService();
755 $data = array_merge($data, self::createPermissionBlockForItem($mail, true));
757 if (empty($data['to']) && !empty($data['cc'])) {
758 $data['to'] = $data['cc'];
761 if (empty($data['to']) && !empty($data['bcc'])) {
762 $data['to'] = $data['bcc'];
768 $object['to'] = $data['to'];
769 $object['tag'] = [['type' => 'Mention', 'href' => $object['to'][0], 'name' => '']];
771 unset($object['cc']);
772 unset($object['bcc']);
774 $data['directMessage'] = true;
776 $data['object'] = $object;
778 $owner = User::getOwnerDataById($mail['uid']);
780 if (!$object_mode && !empty($owner)) {
781 return LDSignature::sign($data, $owner);
788 * Returns the activity type of a given item
792 * @return string with activity type
793 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
794 * @throws \ImagickException
796 private static function getTypeOfItem($item)
800 // Only check for a reshare, if it is a real reshare and no quoted reshare
801 if (strpos($item['body'], "[share") === 0) {
802 $announce = self::getAnnounceArray($item);
803 $reshared = !empty($announce);
808 } elseif ($item['verb'] == Activity::POST) {
809 if ($item['created'] == $item['edited']) {
814 } elseif ($item['verb'] == Activity::LIKE) {
816 } elseif ($item['verb'] == Activity::DISLIKE) {
818 } elseif ($item['verb'] == Activity::ATTEND) {
820 } elseif ($item['verb'] == Activity::ATTENDNO) {
822 } elseif ($item['verb'] == Activity::ATTENDMAYBE) {
823 $type = 'TentativeAccept';
824 } elseif ($item['verb'] == Activity::FOLLOW) {
826 } elseif ($item['verb'] == Activity::TAG) {
836 * Creates the activity or fetches it from the cache
838 * @param integer $item_id
839 * @param boolean $force Force new cache entry
841 * @return array with the activity
844 public static function createCachedActivityFromItem($item_id, $force = false)
846 $cachekey = 'APDelivery:createActivity:' . $item_id;
849 $data = DI::cache()->get($cachekey);
850 if (!is_null($data)) {
855 $data = ActivityPub\Transmitter::createActivityFromItem($item_id);
857 DI::cache()->set($cachekey, $data, Duration::QUARTER_HOUR);
862 * Creates an activity array for a given item id
864 * @param integer $item_id
865 * @param boolean $object_mode Is the activity item is used inside another object?
867 * @return array of activity
870 public static function createActivityFromItem($item_id, $object_mode = false)
872 $item = Item::selectFirst([], ['id' => $item_id, 'parent-network' => Protocol::NATIVE_SUPPORT]);
874 if (!DBA::isResult($item)) {
878 if ($item['wall'] && ($item['uri'] == $item['parent-uri'])) {
879 $owner = User::getOwnerDataById($item['uid']);
880 if (($owner['account-type'] == User::ACCOUNT_TYPE_COMMUNITY) && ($item['author-link'] != $owner['url'])) {
883 // Disguise forum posts as reshares. Will later be converted to a real announce
884 $item['body'] = share_header($item['author-name'], $item['author-link'], $item['author-avatar'],
885 $item['guid'], $item['created'], $item['plink']) . $item['body'] . '[/share]';
890 $condition = ['item-uri' => $item['uri'], 'protocol' => Conversation::PARCEL_ACTIVITYPUB];
891 $conversation = DBA::selectFirst('conversation', ['source'], $condition);
892 if (DBA::isResult($conversation)) {
893 $data = json_decode($conversation['source'], true);
899 $type = self::getTypeOfItem($item);
903 $data = ['@context' => ActivityPub::CONTEXT];
905 if ($item['deleted'] && ($item['gravity'] == GRAVITY_ACTIVITY)) {
907 } elseif ($item['deleted']) {
914 $data['id'] = $item['uri'] . '#' . $type;
915 $data['type'] = $type;
917 if (Item::isForumPost($item) && ($type != 'Announce')) {
918 $data['actor'] = $item['author-link'];
920 $data['actor'] = $item['owner-link'];
923 $data['published'] = DateTimeFormat::utc($item['created'] . '+00:00', DateTimeFormat::ATOM);
925 $data['instrument'] = self::getService();
927 $data = array_merge($data, self::createPermissionBlockForItem($item, false));
929 if (in_array($data['type'], ['Create', 'Update', 'Delete'])) {
930 $data['object'] = self::createNote($item);
931 } elseif ($data['type'] == 'Add') {
932 $data = self::createAddTag($item, $data);
933 } elseif ($data['type'] == 'Announce') {
934 $data = self::createAnnounce($item, $data);
935 } elseif ($data['type'] == 'Follow') {
936 $data['object'] = $item['parent-uri'];
937 } elseif ($data['type'] == 'Undo') {
938 $data['object'] = self::createActivityFromItem($item_id, true);
940 $data['diaspora:guid'] = $item['guid'];
941 if (!empty($item['signed_text'])) {
942 $data['diaspora:like'] = $item['signed_text'];
944 $data['object'] = $item['thr-parent'];
947 if (!empty($item['contact-uid'])) {
948 $uid = $item['contact-uid'];
953 $owner = User::getOwnerDataById($uid);
955 if (!$object_mode && !empty($owner)) {
956 return LDSignature::sign($data, $owner);
961 /// @todo Create "conversation" entry
965 * Creates a location entry for a given item array
969 * @return array with location array
971 private static function createLocation($item)
973 $location = ['type' => 'Place'];
975 if (!empty($item['location'])) {
976 $location['name'] = $item['location'];
981 if (empty($item['coord'])) {
982 $coord = Map::getCoordinates($item['location']);
984 $coords = explode(' ', $item['coord']);
985 if (count($coords) == 2) {
986 $coord = ['lat' => $coords[0], 'lon' => $coords[1]];
990 if (!empty($coord['lat']) && !empty($coord['lon'])) {
991 $location['latitude'] = $coord['lat'];
992 $location['longitude'] = $coord['lon'];
999 * Returns a tag array for a given item array
1001 * @param array $item
1003 * @return array of tags
1004 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1006 private static function createTagList($item)
1010 $terms = Tag::ArrayFromURIId($item['uri-id'], [Tag::HASHTAG, Tag::MENTION, Tag::IMPLICIT_MENTION, Tag::EXCLUSIVE_MENTION]);
1011 foreach ($terms as $term) {
1012 if ($term['type'] == Tag::HASHTAG) {
1013 $url = DI::baseUrl() . '/search?tag=' . urlencode($term['term']);
1014 $tags[] = ['type' => 'Hashtag', 'href' => $url, 'name' => '#' . $term['term']];
1016 $contact = Contact::getDetailsByURL($term['url']);
1017 if (!empty($contact['addr'])) {
1018 $mention = '@' . $contact['addr'];
1020 $mention = '@' . $term['url'];
1023 $tags[] = ['type' => 'Mention', 'href' => $term['url'], 'name' => $mention];
1027 $announce = self::getAnnounceArray($item);
1028 // Mention the original author upon commented reshares
1029 if (!empty($announce['comment'])) {
1030 $tags[] = ['type' => 'Mention', 'href' => $announce['actor']['url'], 'name' => '@' . $announce['actor']['addr']];
1037 * Adds attachment data to the JSON document
1039 * @param array $item Data of the item that is to be posted
1040 * @param string $type Object type
1042 * @return array with attachment data
1043 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1045 private static function createAttachmentList($item, $type)
1049 // Currently deactivated, since it creates side effects on Mastodon and Pleroma.
1050 // It will be reactivated, once this cleared.
1052 $attach_data = BBCode::getAttachmentData($item['body']);
1053 if (!empty($attach_data['url'])) {
1054 $attachment = ['type' => 'Page',
1055 'mediaType' => 'text/html',
1056 'url' => $attach_data['url']];
1058 if (!empty($attach_data['title'])) {
1059 $attachment['name'] = $attach_data['title'];
1062 if (!empty($attach_data['description'])) {
1063 $attachment['summary'] = $attach_data['description'];
1066 if (!empty($attach_data['image'])) {
1067 $imgdata = Images::getInfoFromURLCached($attach_data['image']);
1069 $attachment['icon'] = ['type' => 'Image',
1070 'mediaType' => $imgdata['mime'],
1071 'width' => $imgdata[0],
1072 'height' => $imgdata[1],
1073 'url' => $attach_data['image']];
1077 $attachments[] = $attachment;
1080 $arr = explode('[/attach],', $item['attach']);
1082 foreach ($arr as $r) {
1084 $cnt = preg_match('|\[attach\]href=\"(.*?)\" length=\"(.*?)\" type=\"(.*?)\" title=\"(.*?)\"|', $r, $matches);
1086 $attributes = ['type' => 'Document',
1087 'mediaType' => $matches[3],
1088 'url' => $matches[1],
1091 if (trim($matches[4]) != '') {
1092 $attributes['name'] = trim($matches[4]);
1095 $attachments[] = $attributes;
1100 if ($type != 'Note') {
1101 return $attachments;
1104 // Simplify image codes
1105 $body = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '[img]$3[/img]', $item['body']);
1107 // Grab all pictures without alternative descriptions and create attachments out of them
1108 if (preg_match_all("/\[img\]([^\[\]]*)\[\/img\]/Usi", $body, $pictures)) {
1109 foreach ($pictures[1] as $picture) {
1110 $imgdata = Images::getInfoFromURLCached($picture);
1112 $attachments[] = ['type' => 'Document',
1113 'mediaType' => $imgdata['mime'],
1120 // Grab all pictures with alternative description and create attachments out of them
1121 if (preg_match_all("/\[img=([^\[\]]*)\]([^\[\]]*)\[\/img\]/Usi", $body, $pictures, PREG_SET_ORDER)) {
1122 foreach ($pictures as $picture) {
1123 $imgdata = Images::getInfoFromURLCached($picture[1]);
1125 $attachments[] = ['type' => 'Document',
1126 'mediaType' => $imgdata['mime'],
1127 'url' => $picture[1],
1128 'name' => $picture[2]];
1133 return $attachments;
1137 * Callback function to replace a Friendica style mention in a mention that is used on AP
1139 * @param array $match Matching values for the callback
1140 * @return string Replaced mention
1141 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1143 private static function mentionCallback($match)
1145 if (empty($match[1])) {
1149 $data = Contact::getDetailsByURL($match[1]);
1150 if (empty($data['nick'])) {
1154 return '@[url=' . $data['url'] . ']' . $data['nick'] . '[/url]';
1158 * Remove image elements since they are added as attachment
1160 * @param string $body
1162 * @return string with removed images
1164 private static function removePictures($body)
1166 // Simplify image codes
1167 $body = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '[img]$3[/img]', $body);
1168 $body = preg_replace("/\[img\=(.*?)\](.*?)\[\/img\]/ism", '[img]$1[/img]', $body);
1170 // Now remove local links
1171 $body = preg_replace_callback(
1172 '/\[url=([^\[\]]*)\]\[img\](.*)\[\/img\]\[\/url\]/Usi',
1174 // We remove the link when it is a link to a local photo page
1175 if (Photo::isLocalPage($match[1])) {
1178 // otherwise we just return the link
1179 return '[url]' . $match[1] . '[/url]';
1184 // Remove all pictures
1185 $body = preg_replace("/\[img\]([^\[\]]*)\[\/img\]/Usi", '', $body);
1191 * Fetches the "context" value for a givem item array from the "conversation" table
1193 * @param array $item
1195 * @return string with context url
1196 * @throws \Exception
1198 private static function fetchContextURLForItem($item)
1200 $conversation = DBA::selectFirst('conversation', ['conversation-href', 'conversation-uri'], ['item-uri' => $item['parent-uri']]);
1201 if (DBA::isResult($conversation) && !empty($conversation['conversation-href'])) {
1202 $context_uri = $conversation['conversation-href'];
1203 } elseif (DBA::isResult($conversation) && !empty($conversation['conversation-uri'])) {
1204 $context_uri = $conversation['conversation-uri'];
1206 $context_uri = $item['parent-uri'] . '#context';
1208 return $context_uri;
1212 * Returns if the post contains sensitive content ("nsfw")
1214 * @param integer $uri_id
1217 * @throws \Exception
1219 private static function isSensitive($uri_id)
1221 return DBA::exists('tag-view', ['uri-id' => $uri_id, 'name' => 'nsfw']);
1225 * Creates event data
1227 * @param array $item
1229 * @return array with the event data
1230 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1232 public static function createEvent($item)
1235 $event['name'] = $item['event-summary'];
1236 $event['content'] = BBCode::convert($item['event-desc'], false, 9);
1237 $event['startTime'] = DateTimeFormat::utc($item['event-start'] . '+00:00', DateTimeFormat::ATOM);
1239 if (!$item['event-nofinish']) {
1240 $event['endTime'] = DateTimeFormat::utc($item['event-finish'] . '+00:00', DateTimeFormat::ATOM);
1243 if (!empty($item['event-location'])) {
1244 $item['location'] = $item['event-location'];
1245 $event['location'] = self::createLocation($item);
1252 * Creates a note/article object array
1254 * @param array $item
1256 * @return array with the object data
1257 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1258 * @throws \ImagickException
1260 public static function createNote($item)
1266 if ($item['event-type'] == 'event') {
1268 } elseif (!empty($item['title'])) {
1274 if ($item['deleted']) {
1275 $type = 'Tombstone';
1279 $data['id'] = $item['uri'];
1280 $data['type'] = $type;
1282 if ($item['deleted']) {
1286 $data['summary'] = BBCode::toPlaintext(BBCode::getAbstract($item['body'], Protocol::ACTIVITYPUB));
1288 if ($item['uri'] != $item['thr-parent']) {
1289 $data['inReplyTo'] = $item['thr-parent'];
1291 $data['inReplyTo'] = null;
1294 $data['diaspora:guid'] = $item['guid'];
1295 $data['published'] = DateTimeFormat::utc($item['created'] . '+00:00', DateTimeFormat::ATOM);
1297 if ($item['created'] != $item['edited']) {
1298 $data['updated'] = DateTimeFormat::utc($item['edited'] . '+00:00', DateTimeFormat::ATOM);
1301 $data['url'] = $item['plink'];
1302 $data['attributedTo'] = $item['author-link'];
1303 $data['sensitive'] = self::isSensitive($item['uri-id']);
1304 $data['context'] = self::fetchContextURLForItem($item);
1306 if (!empty($item['title'])) {
1307 $data['name'] = BBCode::toPlaintext($item['title'], false);
1310 $permission_block = self::createPermissionBlockForItem($item, false);
1312 $body = $item['body'];
1314 if (empty($item['uid']) || !Feature::isEnabled($item['uid'], 'explicit_mentions')) {
1315 $body = self::prependMentions($body, $permission_block);
1318 if ($type == 'Note') {
1319 $body = self::removePictures($body);
1320 } elseif (($type == 'Article') && empty($data['summary'])) {
1321 $data['summary'] = BBCode::toPlaintext(Plaintext::shorten(self::removePictures($body), 1000));
1324 if ($type == 'Event') {
1325 $data = array_merge($data, self::createEvent($item));
1327 $regexp = "/[@!]\[url\=([^\[\]]*)\].*?\[\/url\]/ism";
1328 $body = preg_replace_callback($regexp, ['self', 'mentionCallback'], $body);
1330 $data['content'] = BBCode::convert($body, false, 9);
1333 // The regular "content" field does contain a minimized HTML. This is done since systems like
1334 // Mastodon has got problems with - for example - embedded pictures.
1335 // The contentMap does contain the unmodified HTML.
1336 $language = self::getLanguage($item);
1337 if (!empty($language)) {
1338 $regexp = "/[@!]\[url\=([^\[\]]*)\].*?\[\/url\]/ism";
1339 $richbody = preg_replace_callback($regexp, ['self', 'mentionCallback'], $item['body']);
1340 $richbody = BBCode::removeAttachment($richbody);
1342 $data['contentMap'][$language] = BBCode::convert($richbody, false);
1345 $data['source'] = ['content' => $item['body'], 'mediaType' => "text/bbcode"];
1347 if (!empty($item['signed_text']) && ($item['uri'] != $item['thr-parent'])) {
1348 $data['diaspora:comment'] = $item['signed_text'];
1351 $data['attachment'] = self::createAttachmentList($item, $type);
1352 $data['tag'] = self::createTagList($item);
1354 if (empty($data['location']) && (!empty($item['coord']) || !empty($item['location']))) {
1355 $data['location'] = self::createLocation($item);
1358 if (!empty($item['app'])) {
1359 $data['generator'] = ['type' => 'Application', 'name' => $item['app']];
1362 $data = array_merge($data, $permission_block);
1368 * Fetches the language from the post, the user or the system.
1370 * @param array $item
1372 * @return string language string
1374 private static function getLanguage(array $item)
1376 // Try to fetch the language from the post itself
1377 if (!empty($item['language'])) {
1378 $languages = array_keys(json_decode($item['language'], true));
1379 if (!empty($languages[0])) {
1380 return $languages[0];
1384 // Otherwise use the user's language
1385 if (!empty($item['uid'])) {
1386 $user = DBA::selectFirst('user', ['language'], ['uid' => $item['uid']]);
1387 if (!empty($user['language'])) {
1388 return $user['language'];
1392 // And finally just use the system language
1393 return DI::config()->get('system', 'language');
1397 * Creates an an "add tag" entry
1399 * @param array $item
1400 * @param array $data activity data
1402 * @return array with activity data for adding tags
1403 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1404 * @throws \ImagickException
1406 private static function createAddTag($item, $data)
1408 $object = XML::parseString($item['object'], false);
1409 $target = XML::parseString($item["target"], false);
1411 $data['diaspora:guid'] = $item['guid'];
1412 $data['actor'] = $item['author-link'];
1413 $data['target'] = (string)$target->id;
1414 $data['summary'] = BBCode::toPlaintext($item['body']);
1415 $data['object'] = ['id' => (string)$object->id, 'type' => 'tag', 'name' => (string)$object->title, 'content' => (string)$object->content];
1421 * Creates an announce object entry
1423 * @param array $item
1424 * @param array $data activity data
1426 * @return array with activity data
1427 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1428 * @throws \ImagickException
1430 private static function createAnnounce($item, $data)
1432 $orig_body = $item['body'];
1433 $announce = self::getAnnounceArray($item);
1434 if (empty($announce)) {
1435 $data['type'] = 'Create';
1436 $data['object'] = self::createNote($item);
1440 if (empty($announce['comment'])) {
1441 // Pure announce, without a quote
1442 $data['type'] = 'Announce';
1443 $data['object'] = $announce['object']['uri'];
1448 $data['type'] = 'Create';
1449 $item['body'] = $announce['comment'] . "\n" . $announce['object']['plink'];
1450 $data['object'] = self::createNote($item);
1452 /// @todo Finally descide how to implement this in AP. This is a possible way:
1453 $data['object']['attachment'][] = self::createNote($announce['object']);
1455 $data['object']['source']['content'] = $orig_body;
1460 * Return announce related data if the item is an annunce
1462 * @param array $item
1466 public static function getAnnounceArray($item)
1468 $reshared = Item::getShareArray($item);
1469 if (empty($reshared['guid'])) {
1473 $reshared_item = Item::selectFirst([], ['guid' => $reshared['guid']]);
1474 if (!DBA::isResult($reshared_item)) {
1478 if (!in_array($reshared_item['network'], [Protocol::ACTIVITYPUB, Protocol::DFRN])) {
1482 $profile = APContact::getByURL($reshared_item['author-link'], false);
1483 if (empty($profile)) {
1487 return ['object' => $reshared_item, 'actor' => $profile, 'comment' => $reshared['comment']];
1491 * Checks if the provided item array is an announce
1493 * @param array $item
1497 public static function isAnnounce($item)
1499 $announce = self::getAnnounceArray($item);
1500 if (empty($announce)) {
1504 return empty($announce['comment']);
1508 * Creates an activity id for a given contact id
1510 * @param integer $cid Contact ID of target
1512 * @return bool|string activity id
1514 public static function activityIDFromContact($cid)
1516 $contact = DBA::selectFirst('contact', ['uid', 'id', 'created'], ['id' => $cid]);
1517 if (!DBA::isResult($contact)) {
1521 $hash = hash('ripemd128', $contact['uid'].'-'.$contact['id'].'-'.$contact['created']);
1522 $uuid = substr($hash, 0, 8). '-' . substr($hash, 8, 4) . '-' . substr($hash, 12, 4) . '-' . substr($hash, 16, 4) . '-' . substr($hash, 20, 12);
1523 return DI::baseUrl() . '/activity/' . $uuid;
1527 * Transmits a contact suggestion to a given inbox
1529 * @param integer $uid User ID
1530 * @param string $inbox Target inbox
1531 * @param integer $suggestion_id Suggestion ID
1533 * @return boolean was the transmission successful?
1534 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1536 public static function sendContactSuggestion($uid, $inbox, $suggestion_id)
1538 $owner = User::getOwnerDataById($uid);
1540 $suggestion = DI::fsuggest()->getById($suggestion_id);
1542 $data = ['@context' => ActivityPub::CONTEXT,
1543 'id' => DI::baseUrl() . '/activity/' . System::createGUID(),
1544 'type' => 'Announce',
1545 'actor' => $owner['url'],
1546 'object' => $suggestion->url,
1547 'content' => $suggestion->note,
1548 'instrument' => self::getService(),
1549 'to' => [ActivityPub::PUBLIC_COLLECTION],
1552 $signed = LDSignature::sign($data, $owner);
1554 Logger::log('Deliver profile deletion for user ' . $uid . ' to ' . $inbox . ' via ActivityPub', Logger::DEBUG);
1555 return HTTPSignature::transmit($signed, $inbox, $uid);
1559 * Transmits a profile relocation to a given inbox
1561 * @param integer $uid User ID
1562 * @param string $inbox Target inbox
1564 * @return boolean was the transmission successful?
1565 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1567 public static function sendProfileRelocation($uid, $inbox)
1569 $owner = User::getOwnerDataById($uid);
1571 $data = ['@context' => ActivityPub::CONTEXT,
1572 'id' => DI::baseUrl() . '/activity/' . System::createGUID(),
1573 'type' => 'dfrn:relocate',
1574 'actor' => $owner['url'],
1575 'object' => $owner['url'],
1576 'published' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
1577 'instrument' => self::getService(),
1578 'to' => [ActivityPub::PUBLIC_COLLECTION],
1581 $signed = LDSignature::sign($data, $owner);
1583 Logger::log('Deliver profile relocation for user ' . $uid . ' to ' . $inbox . ' via ActivityPub', Logger::DEBUG);
1584 return HTTPSignature::transmit($signed, $inbox, $uid);
1588 * Transmits a profile deletion to a given inbox
1590 * @param integer $uid User ID
1591 * @param string $inbox Target inbox
1593 * @return boolean was the transmission successful?
1594 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1596 public static function sendProfileDeletion($uid, $inbox)
1598 $owner = User::getOwnerDataById($uid);
1600 if (empty($owner)) {
1601 Logger::error('No owner data found, the deletion message cannot be processed.', ['user' => $uid]);
1605 if (empty($owner['uprvkey'])) {
1606 Logger::error('No private key for owner found, the deletion message cannot be processed.', ['user' => $uid]);
1610 $data = ['@context' => ActivityPub::CONTEXT,
1611 'id' => DI::baseUrl() . '/activity/' . System::createGUID(),
1613 'actor' => $owner['url'],
1614 'object' => $owner['url'],
1615 'published' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
1616 'instrument' => self::getService(),
1617 'to' => [ActivityPub::PUBLIC_COLLECTION],
1620 $signed = LDSignature::sign($data, $owner);
1622 Logger::log('Deliver profile deletion for user ' . $uid . ' to ' . $inbox . ' via ActivityPub', Logger::DEBUG);
1623 return HTTPSignature::transmit($signed, $inbox, $uid);
1627 * Transmits a profile change to a given inbox
1629 * @param integer $uid User ID
1630 * @param string $inbox Target inbox
1632 * @return boolean was the transmission successful?
1633 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1634 * @throws \ImagickException
1636 public static function sendProfileUpdate($uid, $inbox)
1638 $owner = User::getOwnerDataById($uid);
1639 $profile = APContact::getByURL($owner['url']);
1641 $data = ['@context' => ActivityPub::CONTEXT,
1642 'id' => DI::baseUrl() . '/activity/' . System::createGUID(),
1644 'actor' => $owner['url'],
1645 'object' => self::getProfile($uid),
1646 'published' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
1647 'instrument' => self::getService(),
1648 'to' => [$profile['followers']],
1651 $signed = LDSignature::sign($data, $owner);
1653 Logger::log('Deliver profile update for user ' . $uid . ' to ' . $inbox . ' via ActivityPub', Logger::DEBUG);
1654 return HTTPSignature::transmit($signed, $inbox, $uid);
1658 * Transmits a given activity to a target
1660 * @param string $activity Type name
1661 * @param string $target Target profile
1662 * @param integer $uid User ID
1664 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1665 * @throws \ImagickException
1666 * @throws \Exception
1668 public static function sendActivity($activity, $target, $uid, $id = '')
1670 $profile = APContact::getByURL($target);
1671 if (empty($profile['inbox'])) {
1672 Logger::warning('No inbox found for target', ['target' => $target, 'profile' => $profile]);
1676 $owner = User::getOwnerDataById($uid);
1679 $id = DI::baseUrl() . '/activity/' . System::createGUID();
1682 $data = ['@context' => ActivityPub::CONTEXT,
1684 'type' => $activity,
1685 'actor' => $owner['url'],
1686 'object' => $profile['url'],
1687 'instrument' => self::getService(),
1688 'to' => [$profile['url']]];
1690 Logger::log('Sending activity ' . $activity . ' to ' . $target . ' for user ' . $uid, Logger::DEBUG);
1692 $signed = LDSignature::sign($data, $owner);
1693 return HTTPSignature::transmit($signed, $profile['inbox'], $uid);
1697 * Transmits a "follow object" activity to a target
1698 * This is a preparation for sending automated "follow" requests when receiving "Announce" messages
1700 * @param string $object Object URL
1701 * @param string $target Target profile
1702 * @param integer $uid User ID
1704 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1705 * @throws \ImagickException
1706 * @throws \Exception
1708 public static function sendFollowObject($object, $target, $uid = 0)
1710 $profile = APContact::getByURL($target);
1711 if (empty($profile['inbox'])) {
1712 Logger::warning('No inbox found for target', ['target' => $target, 'profile' => $profile]);
1717 // Fetch the list of administrators
1718 $admin_mail = explode(',', str_replace(' ', '', DI::config()->get('config', 'admin_email')));
1720 // We need to use some user as a sender. It doesn't care who it will send. We will use an administrator account.
1721 $condition = ['verified' => true, 'blocked' => false, 'account_removed' => false, 'account_expired' => false, 'email' => $admin_mail];
1722 $first_user = DBA::selectFirst('user', ['uid'], $condition);
1723 $uid = $first_user['uid'];
1726 $condition = ['verb' => Activity::FOLLOW, 'uid' => 0, 'parent-uri' => $object,
1727 'author-id' => Contact::getPublicIdByUserId($uid)];
1728 if (Item::exists($condition)) {
1729 Logger::log('Follow for ' . $object . ' for user ' . $uid . ' does already exist.', Logger::DEBUG);
1733 $owner = User::getOwnerDataById($uid);
1735 $data = ['@context' => ActivityPub::CONTEXT,
1736 'id' => DI::baseUrl() . '/activity/' . System::createGUID(),
1738 'actor' => $owner['url'],
1739 'object' => $object,
1740 'instrument' => self::getService(),
1741 'to' => [$profile['url']]];
1743 Logger::log('Sending follow ' . $object . ' to ' . $target . ' for user ' . $uid, Logger::DEBUG);
1745 $signed = LDSignature::sign($data, $owner);
1746 return HTTPSignature::transmit($signed, $profile['inbox'], $uid);
1750 * Transmit a message that the contact request had been accepted
1752 * @param string $target Target profile
1754 * @param integer $uid User ID
1755 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1756 * @throws \ImagickException
1758 public static function sendContactAccept($target, $id, $uid)
1760 $profile = APContact::getByURL($target);
1761 if (empty($profile['inbox'])) {
1762 Logger::warning('No inbox found for target', ['target' => $target, 'profile' => $profile]);
1766 $owner = User::getOwnerDataById($uid);
1767 $data = ['@context' => ActivityPub::CONTEXT,
1768 'id' => DI::baseUrl() . '/activity/' . System::createGUID(),
1770 'actor' => $owner['url'],
1772 'id' => (string)$id,
1774 'actor' => $profile['url'],
1775 'object' => $owner['url']
1777 'instrument' => self::getService(),
1778 'to' => [$profile['url']]];
1780 Logger::debug('Sending accept to ' . $target . ' for user ' . $uid . ' with id ' . $id);
1782 $signed = LDSignature::sign($data, $owner);
1783 HTTPSignature::transmit($signed, $profile['inbox'], $uid);
1787 * Reject a contact request or terminates the contact relation
1789 * @param string $target Target profile
1791 * @param integer $uid User ID
1792 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1793 * @throws \ImagickException
1795 public static function sendContactReject($target, $id, $uid)
1797 $profile = APContact::getByURL($target);
1798 if (empty($profile['inbox'])) {
1799 Logger::warning('No inbox found for target', ['target' => $target, 'profile' => $profile]);
1803 $owner = User::getOwnerDataById($uid);
1804 $data = ['@context' => ActivityPub::CONTEXT,
1805 'id' => DI::baseUrl() . '/activity/' . System::createGUID(),
1807 'actor' => $owner['url'],
1809 'id' => (string)$id,
1811 'actor' => $profile['url'],
1812 'object' => $owner['url']
1814 'instrument' => self::getService(),
1815 'to' => [$profile['url']]];
1817 Logger::debug('Sending reject to ' . $target . ' for user ' . $uid . ' with id ' . $id);
1819 $signed = LDSignature::sign($data, $owner);
1820 HTTPSignature::transmit($signed, $profile['inbox'], $uid);
1824 * Transmits a message that we don't want to follow this contact anymore
1826 * @param string $target Target profile
1827 * @param integer $uid User ID
1828 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1829 * @throws \ImagickException
1830 * @throws \Exception
1832 public static function sendContactUndo($target, $cid, $uid)
1834 $profile = APContact::getByURL($target);
1835 if (empty($profile['inbox'])) {
1836 Logger::warning('No inbox found for target', ['target' => $target, 'profile' => $profile]);
1840 $object_id = self::activityIDFromContact($cid);
1841 if (empty($object_id)) {
1845 $id = DI::baseUrl() . '/activity/' . System::createGUID();
1847 $owner = User::getOwnerDataById($uid);
1848 $data = ['@context' => ActivityPub::CONTEXT,
1851 'actor' => $owner['url'],
1852 'object' => ['id' => $object_id, 'type' => 'Follow',
1853 'actor' => $owner['url'],
1854 'object' => $profile['url']],
1855 'instrument' => self::getService(),
1856 'to' => [$profile['url']]];
1858 Logger::log('Sending undo to ' . $target . ' for user ' . $uid . ' with id ' . $id, Logger::DEBUG);
1860 $signed = LDSignature::sign($data, $owner);
1861 HTTPSignature::transmit($signed, $profile['inbox'], $uid);
1864 private static function prependMentions($body, array $permission_block)
1866 if (DI::config()->get('system', 'disable_implicit_mentions')) {
1872 foreach ($permission_block['to'] as $profile_url) {
1873 $profile = Contact::getDetailsByURL($profile_url);
1874 if (!empty($profile['addr'])
1875 && $profile['contact-type'] != Contact::TYPE_COMMUNITY
1876 && !strstr($body, $profile['addr'])
1877 && !strstr($body, $profile_url)
1879 $mentions[] = '@[url=' . $profile_url . ']' . $profile['nick'] . '[/url]';
1883 $mentions[] = $body;
1885 return implode(' ', $mentions);