3 * @copyright Copyright (C) 2020, Friendica
5 * @license GNU AGPL version 3 or any later version
7 * This program is free software: you can redistribute it and/or modify
8 * it under the terms of the GNU Affero General Public License as
9 * published by the Free Software Foundation, either version 3 of the
10 * License, or (at your option) any later version.
12 * This program is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU Affero General Public License for more details.
17 * You should have received a copy of the GNU Affero General Public License
18 * along with this program. If not, see <https://www.gnu.org/licenses/>.
22 namespace Friendica\Protocol\ActivityPub;
24 use Friendica\Content\Feature;
25 use Friendica\Content\Text\BBCode;
26 use Friendica\Content\Text\Plaintext;
27 use Friendica\Core\Cache\Duration;
28 use Friendica\Core\Logger;
29 use Friendica\Core\Protocol;
30 use Friendica\Core\System;
31 use Friendica\Database\DBA;
33 use Friendica\Model\APContact;
34 use Friendica\Model\Contact;
35 use Friendica\Model\Conversation;
36 use Friendica\Model\Item;
37 use Friendica\Model\Profile;
38 use Friendica\Model\Photo;
39 use Friendica\Model\Term;
40 use Friendica\Model\User;
41 use Friendica\Protocol\Activity;
42 use Friendica\Protocol\ActivityPub;
43 use Friendica\Util\DateTimeFormat;
44 use Friendica\Util\HTTPSignature;
45 use Friendica\Util\Images;
46 use Friendica\Util\JsonLD;
47 use Friendica\Util\LDSignature;
48 use Friendica\Util\Map;
49 use Friendica\Util\Network;
50 use Friendica\Util\XML;
52 require_once 'include/api.php';
53 require_once 'mod/share.php';
56 * ActivityPub Transmitter Protocol class
64 * collects the lost of followers of the given owner
66 * @param array $owner Owner array
67 * @param integer $page Page number
69 * @return array of owners
70 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
72 public static function getFollowers($owner, $page = null)
74 $condition = ['rel' => [Contact::FOLLOWER, Contact::FRIEND], 'network' => Protocol::NATIVE_SUPPORT, '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::NATIVE_SUPPORT, '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 // Only list "Create" activity objects here, no reshares
197 if (is_array($activity['object']) && ($activity['type'] == 'Create')) {
198 $list[] = $activity['object'];
203 $data['next'] = DI::baseUrl() . '/outbox/' . $owner['nickname'] . '?page=' . ($page + 1);
206 $data['partOf'] = DI::baseUrl() . '/outbox/' . $owner['nickname'];
208 $data['orderedItems'] = $list;
215 * Return the service array containing information the used software and it's url
217 * @return array with service data
219 private static function getService()
221 return ['type' => 'Service',
222 'name' => FRIENDICA_PLATFORM . " '" . FRIENDICA_CODENAME . "' " . FRIENDICA_VERSION . '-' . DB_UPDATE_VERSION,
223 'url' => DI::baseUrl()->get()];
227 * Return the ActivityPub profile of the given user
229 * @param integer $uid User ID
230 * @return array with profile data
231 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
233 public static function getProfile($uid)
235 $condition = ['uid' => $uid, 'blocked' => false, 'account_expired' => false,
236 'account_removed' => false, 'verified' => true];
237 $fields = ['guid', 'nickname', 'pubkey', 'account-type', 'page-flags'];
238 $user = DBA::selectFirst('user', $fields, $condition);
239 if (!DBA::isResult($user)) {
243 $fields = ['locality', 'region', 'country-name'];
244 $profile = DBA::selectFirst('profile', $fields, ['uid' => $uid]);
245 if (!DBA::isResult($profile)) {
249 $fields = ['name', 'url', 'location', 'about', 'avatar', 'photo'];
250 $contact = DBA::selectFirst('contact', $fields, ['uid' => $uid, 'self' => true]);
251 if (!DBA::isResult($contact)) {
255 $data = ['@context' => ActivityPub::CONTEXT];
256 $data['id'] = $contact['url'];
257 $data['diaspora:guid'] = $user['guid'];
258 $data['type'] = ActivityPub::ACCOUNT_TYPES[$user['account-type']];
259 $data['following'] = DI::baseUrl() . '/following/' . $user['nickname'];
260 $data['followers'] = DI::baseUrl() . '/followers/' . $user['nickname'];
261 $data['inbox'] = DI::baseUrl() . '/inbox/' . $user['nickname'];
262 $data['outbox'] = DI::baseUrl() . '/outbox/' . $user['nickname'];
263 $data['preferredUsername'] = $user['nickname'];
264 $data['name'] = $contact['name'];
265 $data['vcard:hasAddress'] = ['@type' => 'vcard:Home', 'vcard:country-name' => $profile['country-name'],
266 'vcard:region' => $profile['region'], 'vcard:locality' => $profile['locality']];
267 $data['summary'] = $contact['about'];
268 $data['url'] = $contact['url'];
269 $data['manuallyApprovesFollowers'] = in_array($user['page-flags'], [User::PAGE_FLAGS_NORMAL, User::PAGE_FLAGS_PRVGROUP]);
270 $data['publicKey'] = ['id' => $contact['url'] . '#main-key',
271 'owner' => $contact['url'],
272 'publicKeyPem' => $user['pubkey']];
273 $data['endpoints'] = ['sharedInbox' => DI::baseUrl() . '/inbox'];
274 $data['icon'] = ['type' => 'Image',
275 'url' => $contact['photo']];
277 $data['generator'] = self::getService();
279 // tags: https://kitty.town/@inmysocks/100656097926961126.json
284 * @param string $username
286 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
288 public static function getDeletedUser($username)
291 '@context' => ActivityPub::CONTEXT,
292 'id' => DI::baseUrl() . '/profile/' . $username,
293 'type' => 'Tombstone',
294 'published' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
295 'updated' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
296 'deleted' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
301 * Returns an array with permissions of a given item array
305 * @return array with permissions
306 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
307 * @throws \ImagickException
309 private static function fetchPermissionBlockFromConversation($item)
311 if (empty($item['thr-parent'])) {
315 $condition = ['item-uri' => $item['thr-parent'], 'protocol' => Conversation::PARCEL_ACTIVITYPUB];
316 $conversation = DBA::selectFirst('conversation', ['source'], $condition);
317 if (!DBA::isResult($conversation)) {
321 $activity = json_decode($conversation['source'], true);
323 $actor = JsonLD::fetchElement($activity, 'actor', 'id');
324 $profile = APContact::getByURL($actor);
326 $item_profile = APContact::getByURL($item['author-link']);
327 $exclude[] = $item['author-link'];
329 if ($item['gravity'] == GRAVITY_PARENT) {
330 $exclude[] = $item['owner-link'];
333 $permissions['to'][] = $actor;
335 foreach (['to', 'cc', 'bto', 'bcc'] as $element) {
336 if (empty($activity[$element])) {
339 if (is_string($activity[$element])) {
340 $activity[$element] = [$activity[$element]];
343 foreach ($activity[$element] as $receiver) {
344 if ($receiver == $profile['followers'] && !empty($item_profile['followers'])) {
345 $permissions[$element][] = $item_profile['followers'];
346 } elseif (!in_array($receiver, $exclude)) {
347 $permissions[$element][] = $receiver;
355 * Creates an array of permissions from an item thread
357 * @param array $item Item array
358 * @param boolean $blindcopy addressing via "bcc" or "cc"?
359 * @param integer $last_id Last item id for adding receivers
360 * @param boolean $forum_mode "true" means that we are sending content to a forum
362 * @return array with permission data
363 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
364 * @throws \ImagickException
366 private static function createPermissionBlockForItem($item, $blindcopy, $last_id = 0, $forum_mode = false)
369 $last_id = $item['id'];
374 // Check if we should always deliver our stuff via BCC
375 if (!empty($item['uid'])) {
376 $profile = Profile::getByUID($item['uid']);
377 if (!empty($profile)) {
378 $always_bcc = $profile['hide-friends'];
382 if (DI::config()->get('system', 'ap_always_bcc')) {
386 if (self::isAnnounce($item) || DI::config()->get('debug', 'total_ap_delivery')) {
387 // Will be activated in a later step
388 $networks = Protocol::FEDERATED;
390 // For now only send to these contacts:
391 $networks = [Protocol::ACTIVITYPUB, Protocol::OSTATUS];
394 $data = ['to' => [], 'cc' => [], 'bcc' => []];
396 if ($item['gravity'] == GRAVITY_PARENT) {
397 $actor_profile = APContact::getByURL($item['owner-link']);
399 $actor_profile = APContact::getByURL($item['author-link']);
402 $terms = Term::tagArrayFromItemId($item['id'], [Term::MENTION, Term::IMPLICIT_MENTION]);
404 if ($item['private'] != Item::PRIVATE) {
405 // Directly mention the original author upon a quoted reshare.
406 // Else just ensure that the original author receives the reshare.
407 $announce = self::getAnnounceArray($item);
408 if (!empty($announce['comment'])) {
409 $data['to'][] = $announce['actor']['url'];
410 } elseif (!empty($announce)) {
411 $data['cc'][] = $announce['actor']['url'];
414 $data = array_merge($data, self::fetchPermissionBlockFromConversation($item));
416 // Check if the item is completely public or unlisted
417 if ($item['private'] == Item::PUBLIC) {
418 $data['to'][] = ActivityPub::PUBLIC_COLLECTION;
420 $data['cc'][] = ActivityPub::PUBLIC_COLLECTION;
423 foreach ($terms as $term) {
424 $profile = APContact::getByURL($term['url'], false);
425 if (!empty($profile)) {
426 $data['to'][] = $profile['url'];
430 $receiver_list = Item::enumeratePermissions($item, true);
432 foreach ($terms as $term) {
433 $cid = Contact::getIdForURL($term['url'], $item['uid']);
434 if (!empty($cid) && in_array($cid, $receiver_list)) {
435 $contact = DBA::selectFirst('contact', ['url', 'network', 'protocol'], ['id' => $cid]);
436 if (!DBA::isResult($contact) || (!in_array($contact['network'], $networks) && ($contact['protocol'] != Protocol::ACTIVITYPUB))) {
440 if (!empty($profile = APContact::getByURL($contact['url'], false))) {
441 $data['to'][] = $profile['url'];
446 foreach ($receiver_list as $receiver) {
447 $contact = DBA::selectFirst('contact', ['url', 'hidden', 'network', 'protocol'], ['id' => $receiver]);
448 if (!DBA::isResult($contact) || (!in_array($contact['network'], $networks) && ($contact['protocol'] != Protocol::ACTIVITYPUB))) {
452 if (!empty($profile = APContact::getByURL($contact['url'], false))) {
453 if ($contact['hidden'] || $always_bcc) {
454 $data['bcc'][] = $profile['url'];
456 $data['cc'][] = $profile['url'];
462 if (!empty($item['parent'])) {
463 $parents = Item::select(['id', 'author-link', 'owner-link', 'gravity', 'uri'], ['parent' => $item['parent']]);
464 while ($parent = Item::fetch($parents)) {
465 if ($parent['gravity'] == GRAVITY_PARENT) {
466 $profile = APContact::getByURL($parent['owner-link'], false);
467 if (!empty($profile)) {
468 if ($item['gravity'] != GRAVITY_PARENT) {
469 // Comments to forums are directed to the forum
470 // But comments to forums aren't directed to the followers collection
471 if ($profile['type'] == 'Group') {
472 $data['to'][] = $profile['url'];
474 $data['cc'][] = $profile['url'];
475 if (($item['private'] != Item::PRIVATE) && $item['private'] && !empty($actor_profile['followers'])) {
476 $data['cc'][] = $actor_profile['followers'];
480 // Public thread parent post always are directed to the followers
481 if (($item['private'] != Item::PRIVATE) && !$forum_mode) {
482 $data['cc'][] = $actor_profile['followers'];
488 // Don't include data from future posts
489 if ($parent['id'] >= $last_id) {
493 $profile = APContact::getByURL($parent['author-link'], false);
494 if (!empty($profile)) {
495 if (($profile['type'] == 'Group') || ($parent['uri'] == $item['thr-parent'])) {
496 $data['to'][] = $profile['url'];
498 $data['cc'][] = $profile['url'];
502 DBA::close($parents);
505 $data['to'] = array_unique($data['to']);
506 $data['cc'] = array_unique($data['cc']);
507 $data['bcc'] = array_unique($data['bcc']);
509 if (($key = array_search($item['author-link'], $data['to'])) !== false) {
510 unset($data['to'][$key]);
513 if (($key = array_search($item['author-link'], $data['cc'])) !== false) {
514 unset($data['cc'][$key]);
517 if (($key = array_search($item['author-link'], $data['bcc'])) !== false) {
518 unset($data['bcc'][$key]);
521 foreach ($data['to'] as $to) {
522 if (($key = array_search($to, $data['cc'])) !== false) {
523 unset($data['cc'][$key]);
526 if (($key = array_search($to, $data['bcc'])) !== false) {
527 unset($data['bcc'][$key]);
531 foreach ($data['cc'] as $cc) {
532 if (($key = array_search($cc, $data['bcc'])) !== false) {
533 unset($data['bcc'][$key]);
537 $receivers = ['to' => array_values($data['to']), 'cc' => array_values($data['cc']), 'bcc' => array_values($data['bcc'])];
540 unset($receivers['bcc']);
547 * Check if an inbox is archived
549 * @param string $url Inbox url
551 * @return boolean "true" if inbox is archived
553 private static function archivedInbox($url)
555 return DBA::exists('inbox-status', ['url' => $url, 'archive' => true]);
559 * Fetches a list of inboxes of followers of a given user
561 * @param integer $uid User ID
562 * @param boolean $personal fetch personal inboxes
564 * @return array of follower inboxes
565 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
566 * @throws \ImagickException
568 public static function fetchTargetInboxesforUser($uid, $personal = false)
572 if (DI::config()->get('debug', 'total_ap_delivery')) {
573 // Will be activated in a later step
574 $networks = Protocol::FEDERATED;
576 // For now only send to these contacts:
577 $networks = [Protocol::ACTIVITYPUB, Protocol::OSTATUS];
580 $condition = ['uid' => $uid, 'archive' => false, 'pending' => false];
583 $condition['rel'] = [Contact::FOLLOWER, Contact::FRIEND];
586 $contacts = DBA::select('contact', ['url', 'network', 'protocol'], $condition);
587 while ($contact = DBA::fetch($contacts)) {
588 if (Contact::isLocal($contact['url'])) {
592 if (!in_array($contact['network'], $networks) && ($contact['protocol'] != Protocol::ACTIVITYPUB)) {
596 if (Network::isUrlBlocked($contact['url'])) {
600 $profile = APContact::getByURL($contact['url'], false);
601 if (!empty($profile)) {
602 if (empty($profile['sharedinbox']) || $personal) {
603 $target = $profile['inbox'];
605 $target = $profile['sharedinbox'];
607 if (!self::archivedInbox($target)) {
608 $inboxes[$target] = $target;
612 DBA::close($contacts);
618 * Fetches an array of inboxes for the given item and user
620 * @param array $item Item array
621 * @param integer $uid User ID
622 * @param boolean $personal fetch personal inboxes
623 * @param integer $last_id Last item id for adding receivers
624 * @param boolean $forum_mode "true" means that we are sending content to a forum
625 * @return array with inboxes
626 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
627 * @throws \ImagickException
629 public static function fetchTargetInboxes($item, $uid, $personal = false, $last_id = 0, $forum_mode = false)
631 $permissions = self::createPermissionBlockForItem($item, true, $last_id, $forum_mode);
632 if (empty($permissions)) {
638 if ($item['gravity'] == GRAVITY_ACTIVITY) {
639 $item_profile = APContact::getByURL($item['author-link'], false);
641 $item_profile = APContact::getByURL($item['owner-link'], false);
644 foreach (['to', 'cc', 'bto', 'bcc'] as $element) {
645 if (empty($permissions[$element])) {
649 $blindcopy = in_array($element, ['bto', 'bcc']);
651 foreach ($permissions[$element] as $receiver) {
652 if (Network::isUrlBlocked($receiver)) {
656 if ($receiver == $item_profile['followers']) {
657 $inboxes = array_merge($inboxes, self::fetchTargetInboxesforUser($uid, $personal));
659 if (Contact::isLocal($receiver)) {
663 $profile = APContact::getByURL($receiver, false);
664 if (!empty($profile)) {
665 if (empty($profile['sharedinbox']) || $personal || $blindcopy) {
666 $target = $profile['inbox'];
668 $target = $profile['sharedinbox'];
670 if (!self::archivedInbox($target)) {
671 $inboxes[$target] = $target;
682 * Creates an array in the structure of the item table for a given mail id
684 * @param integer $mail_id
689 public static function ItemArrayFromMail($mail_id)
691 $mail = DBA::selectFirst('mail', [], ['id' => $mail_id]);
692 if (!DBA::isResult($mail)) {
696 $reply = DBA::selectFirst('mail', ['uri'], ['parent-uri' => $mail['parent-uri'], 'reply' => false]);
698 // Making the post more compatible for Mastodon by:
699 // - Making it a note and not an article (no title)
700 // - Moving the title into the "summary" field that is used as a "content warning"
701 $mail['body'] = '[abstract]' . $mail['title'] . "[/abstract]\n" . $mail['body'];
704 $mail['author-link'] = $mail['owner-link'] = $mail['from-url'];
705 $mail['allow_cid'] = '<'.$mail['contact-id'].'>';
706 $mail['allow_gid'] = '';
707 $mail['deny_cid'] = '';
708 $mail['deny_gid'] = '';
709 $mail['private'] = true;
710 $mail['deleted'] = false;
711 $mail['edited'] = $mail['created'];
712 $mail['plink'] = $mail['uri'];
713 $mail['thr-parent'] = $reply['uri'];
714 $mail['gravity'] = ($mail['reply'] ? GRAVITY_COMMENT: GRAVITY_PARENT);
716 $mail['event-type'] = '';
717 $mail['attach'] = '';
725 * Creates an activity array for a given mail id
727 * @param integer $mail_id
728 * @param boolean $object_mode Is the activity item is used inside another object?
730 * @return array of activity
733 public static function createActivityFromMail($mail_id, $object_mode = false)
735 $mail = self::ItemArrayFromMail($mail_id);
736 $object = self::createNote($mail);
739 $data = ['@context' => ActivityPub::CONTEXT];
744 $data['id'] = $mail['uri'] . '#Create';
745 $data['type'] = 'Create';
746 $data['actor'] = $mail['author-link'];
747 $data['published'] = DateTimeFormat::utc($mail['created'] . '+00:00', DateTimeFormat::ATOM);
748 $data['instrument'] = self::getService();
749 $data = array_merge($data, self::createPermissionBlockForItem($mail, true));
751 if (empty($data['to']) && !empty($data['cc'])) {
752 $data['to'] = $data['cc'];
755 if (empty($data['to']) && !empty($data['bcc'])) {
756 $data['to'] = $data['bcc'];
762 $object['to'] = $data['to'];
763 $object['tag'] = [['type' => 'Mention', 'href' => $object['to'][0], 'name' => '']];
765 unset($object['cc']);
766 unset($object['bcc']);
768 $data['directMessage'] = true;
770 $data['object'] = $object;
772 $owner = User::getOwnerDataById($mail['uid']);
774 if (!$object_mode && !empty($owner)) {
775 return LDSignature::sign($data, $owner);
782 * Returns the activity type of a given item
786 * @return string with activity type
787 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
788 * @throws \ImagickException
790 private static function getTypeOfItem($item)
794 // Only check for a reshare, if it is a real reshare and no quoted reshare
795 if (strpos($item['body'], "[share") === 0) {
796 $announce = self::getAnnounceArray($item);
797 $reshared = !empty($announce);
802 } elseif ($item['verb'] == Activity::POST) {
803 if ($item['created'] == $item['edited']) {
808 } elseif ($item['verb'] == Activity::LIKE) {
810 } elseif ($item['verb'] == Activity::DISLIKE) {
812 } elseif ($item['verb'] == Activity::ATTEND) {
814 } elseif ($item['verb'] == Activity::ATTENDNO) {
816 } elseif ($item['verb'] == Activity::ATTENDMAYBE) {
817 $type = 'TentativeAccept';
818 } elseif ($item['verb'] == Activity::FOLLOW) {
820 } elseif ($item['verb'] == Activity::TAG) {
830 * Creates the activity or fetches it from the cache
832 * @param integer $item_id
833 * @param boolean $force Force new cache entry
835 * @return array with the activity
838 public static function createCachedActivityFromItem($item_id, $force = false)
840 $cachekey = 'APDelivery:createActivity:' . $item_id;
843 $data = DI::cache()->get($cachekey);
844 if (!is_null($data)) {
849 $data = ActivityPub\Transmitter::createActivityFromItem($item_id);
851 DI::cache()->set($cachekey, $data, Duration::QUARTER_HOUR);
856 * Creates an activity array for a given item id
858 * @param integer $item_id
859 * @param boolean $object_mode Is the activity item is used inside another object?
861 * @return array of activity
864 public static function createActivityFromItem($item_id, $object_mode = false)
866 $item = Item::selectFirst([], ['id' => $item_id, 'parent-network' => Protocol::NATIVE_SUPPORT]);
868 if (!DBA::isResult($item)) {
872 if ($item['wall'] && ($item['uri'] == $item['parent-uri'])) {
873 $owner = User::getOwnerDataById($item['uid']);
874 if (($owner['account-type'] == User::ACCOUNT_TYPE_COMMUNITY) && ($item['author-link'] != $owner['url'])) {
877 // Disguise forum posts as reshares. Will later be converted to a real announce
878 $item['body'] = share_header($item['author-name'], $item['author-link'], $item['author-avatar'],
879 $item['guid'], $item['created'], $item['plink']) . $item['body'] . '[/share]';
884 $condition = ['item-uri' => $item['uri'], 'protocol' => Conversation::PARCEL_ACTIVITYPUB];
885 $conversation = DBA::selectFirst('conversation', ['source'], $condition);
886 if (DBA::isResult($conversation)) {
887 $data = json_decode($conversation['source'], true);
893 $type = self::getTypeOfItem($item);
897 $data = ['@context' => ActivityPub::CONTEXT];
899 if ($item['deleted'] && ($item['gravity'] == GRAVITY_ACTIVITY)) {
901 } elseif ($item['deleted']) {
908 $data['id'] = $item['uri'] . '#' . $type;
909 $data['type'] = $type;
911 if (Item::isForumPost($item) && ($type != 'Announce')) {
912 $data['actor'] = $item['author-link'];
914 $data['actor'] = $item['owner-link'];
917 $data['published'] = DateTimeFormat::utc($item['created'] . '+00:00', DateTimeFormat::ATOM);
919 $data['instrument'] = self::getService();
921 $data = array_merge($data, self::createPermissionBlockForItem($item, false));
923 if (in_array($data['type'], ['Create', 'Update', 'Delete'])) {
924 $data['object'] = self::createNote($item);
925 } elseif ($data['type'] == 'Add') {
926 $data = self::createAddTag($item, $data);
927 } elseif ($data['type'] == 'Announce') {
928 $data = self::createAnnounce($item, $data);
929 } elseif ($data['type'] == 'Follow') {
930 $data['object'] = $item['parent-uri'];
931 } elseif ($data['type'] == 'Undo') {
932 $data['object'] = self::createActivityFromItem($item_id, true);
934 $data['diaspora:guid'] = $item['guid'];
935 if (!empty($item['signed_text'])) {
936 $data['diaspora:like'] = $item['signed_text'];
938 $data['object'] = $item['thr-parent'];
941 if (!empty($item['contact-uid'])) {
942 $uid = $item['contact-uid'];
947 $owner = User::getOwnerDataById($uid);
949 if (!$object_mode && !empty($owner)) {
950 return LDSignature::sign($data, $owner);
955 /// @todo Create "conversation" entry
959 * Creates a location entry for a given item array
963 * @return array with location array
965 private static function createLocation($item)
967 $location = ['type' => 'Place'];
969 if (!empty($item['location'])) {
970 $location['name'] = $item['location'];
975 if (empty($item['coord'])) {
976 $coord = Map::getCoordinates($item['location']);
978 $coords = explode(' ', $item['coord']);
979 if (count($coords) == 2) {
980 $coord = ['lat' => $coords[0], 'lon' => $coords[1]];
984 if (!empty($coord['lat']) && !empty($coord['lon'])) {
985 $location['latitude'] = $coord['lat'];
986 $location['longitude'] = $coord['lon'];
993 * Returns a tag array for a given item array
997 * @return array of tags
998 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1000 private static function createTagList($item)
1004 $terms = Term::tagArrayFromItemId($item['id'], [Term::HASHTAG, Term::MENTION, Term::IMPLICIT_MENTION]);
1005 foreach ($terms as $term) {
1006 if ($term['type'] == Term::HASHTAG) {
1007 $url = DI::baseUrl() . '/search?tag=' . urlencode($term['term']);
1008 $tags[] = ['type' => 'Hashtag', 'href' => $url, 'name' => '#' . $term['term']];
1009 } elseif ($term['type'] == Term::MENTION || $term['type'] == Term::IMPLICIT_MENTION) {
1010 $contact = Contact::getDetailsByURL($term['url']);
1011 if (!empty($contact['addr'])) {
1012 $mention = '@' . $contact['addr'];
1014 $mention = '@' . $term['url'];
1017 $tags[] = ['type' => 'Mention', 'href' => $term['url'], 'name' => $mention];
1021 $announce = self::getAnnounceArray($item);
1022 // Mention the original author upon commented reshares
1023 if (!empty($announce['comment'])) {
1024 $tags[] = ['type' => 'Mention', 'href' => $announce['actor']['url'], 'name' => '@' . $announce['actor']['addr']];
1031 * Adds attachment data to the JSON document
1033 * @param array $item Data of the item that is to be posted
1034 * @param string $type Object type
1036 * @return array with attachment data
1037 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1039 private static function createAttachmentList($item, $type)
1043 // Currently deactivated, since it creates side effects on Mastodon and Pleroma.
1044 // It will be reactivated, once this cleared.
1046 $attach_data = BBCode::getAttachmentData($item['body']);
1047 if (!empty($attach_data['url'])) {
1048 $attachment = ['type' => 'Page',
1049 'mediaType' => 'text/html',
1050 'url' => $attach_data['url']];
1052 if (!empty($attach_data['title'])) {
1053 $attachment['name'] = $attach_data['title'];
1056 if (!empty($attach_data['description'])) {
1057 $attachment['summary'] = $attach_data['description'];
1060 if (!empty($attach_data['image'])) {
1061 $imgdata = Images::getInfoFromURLCached($attach_data['image']);
1063 $attachment['icon'] = ['type' => 'Image',
1064 'mediaType' => $imgdata['mime'],
1065 'width' => $imgdata[0],
1066 'height' => $imgdata[1],
1067 'url' => $attach_data['image']];
1071 $attachments[] = $attachment;
1074 $arr = explode('[/attach],', $item['attach']);
1076 foreach ($arr as $r) {
1078 $cnt = preg_match('|\[attach\]href=\"(.*?)\" length=\"(.*?)\" type=\"(.*?)\" title=\"(.*?)\"|', $r, $matches);
1080 $attributes = ['type' => 'Document',
1081 'mediaType' => $matches[3],
1082 'url' => $matches[1],
1085 if (trim($matches[4]) != '') {
1086 $attributes['name'] = trim($matches[4]);
1089 $attachments[] = $attributes;
1094 if ($type != 'Note') {
1095 return $attachments;
1098 // Simplify image codes
1099 $body = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '[img]$3[/img]', $item['body']);
1101 // Grab all pictures without alternative descriptions and create attachments out of them
1102 if (preg_match_all("/\[img\]([^\[\]]*)\[\/img\]/Usi", $body, $pictures)) {
1103 foreach ($pictures[1] as $picture) {
1104 $imgdata = Images::getInfoFromURLCached($picture);
1106 $attachments[] = ['type' => 'Document',
1107 'mediaType' => $imgdata['mime'],
1114 // Grab all pictures with alternative description and create attachments out of them
1115 if (preg_match_all("/\[img=([^\[\]]*)\]([^\[\]]*)\[\/img\]/Usi", $body, $pictures, PREG_SET_ORDER)) {
1116 foreach ($pictures as $picture) {
1117 $imgdata = Images::getInfoFromURLCached($picture[1]);
1119 $attachments[] = ['type' => 'Document',
1120 'mediaType' => $imgdata['mime'],
1121 'url' => $picture[1],
1122 'name' => $picture[2]];
1127 return $attachments;
1131 * Callback function to replace a Friendica style mention in a mention that is used on AP
1133 * @param array $match Matching values for the callback
1134 * @return string Replaced mention
1135 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1137 private static function mentionCallback($match)
1139 if (empty($match[1])) {
1143 $data = Contact::getDetailsByURL($match[1]);
1144 if (empty($data['nick'])) {
1148 return '@[url=' . $data['url'] . ']' . $data['nick'] . '[/url]';
1152 * Remove image elements since they are added as attachment
1154 * @param string $body
1156 * @return string with removed images
1158 private static function removePictures($body)
1160 // Simplify image codes
1161 $body = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '[img]$3[/img]', $body);
1162 $body = preg_replace("/\[img\=(.*?)\](.*?)\[\/img\]/ism", '[img]$1[/img]', $body);
1164 // Now remove local links
1165 $body = preg_replace_callback(
1166 '/\[url=([^\[\]]*)\]\[img\](.*)\[\/img\]\[\/url\]/Usi',
1168 // We remove the link when it is a link to a local photo page
1169 if (Photo::isLocalPage($match[1])) {
1172 // otherwise we just return the link
1173 return '[url]' . $match[1] . '[/url]';
1178 // Remove all pictures
1179 $body = preg_replace("/\[img\]([^\[\]]*)\[\/img\]/Usi", '', $body);
1185 * Fetches the "context" value for a givem item array from the "conversation" table
1187 * @param array $item
1189 * @return string with context url
1190 * @throws \Exception
1192 private static function fetchContextURLForItem($item)
1194 $conversation = DBA::selectFirst('conversation', ['conversation-href', 'conversation-uri'], ['item-uri' => $item['parent-uri']]);
1195 if (DBA::isResult($conversation) && !empty($conversation['conversation-href'])) {
1196 $context_uri = $conversation['conversation-href'];
1197 } elseif (DBA::isResult($conversation) && !empty($conversation['conversation-uri'])) {
1198 $context_uri = $conversation['conversation-uri'];
1200 $context_uri = $item['parent-uri'] . '#context';
1202 return $context_uri;
1206 * Returns if the post contains sensitive content ("nsfw")
1208 * @param integer $item_id
1211 * @throws \Exception
1213 private static function isSensitive($item_id)
1215 $condition = ['otype' => TERM_OBJ_POST, 'oid' => $item_id, 'type' => TERM_HASHTAG, 'term' => 'nsfw'];
1216 return DBA::exists('term', $condition);
1220 * Creates event data
1222 * @param array $item
1224 * @return array with the event data
1225 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1227 public static function createEvent($item)
1230 $event['name'] = $item['event-summary'];
1231 $event['content'] = BBCode::convert($item['event-desc'], false, 9);
1232 $event['startTime'] = DateTimeFormat::utc($item['event-start'] . '+00:00', DateTimeFormat::ATOM);
1234 if (!$item['event-nofinish']) {
1235 $event['endTime'] = DateTimeFormat::utc($item['event-finish'] . '+00:00', DateTimeFormat::ATOM);
1238 if (!empty($item['event-location'])) {
1239 $item['location'] = $item['event-location'];
1240 $event['location'] = self::createLocation($item);
1247 * Creates a note/article object array
1249 * @param array $item
1251 * @return array with the object data
1252 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1253 * @throws \ImagickException
1255 public static function createNote($item)
1261 if ($item['event-type'] == 'event') {
1263 } elseif (!empty($item['title'])) {
1269 if ($item['deleted']) {
1270 $type = 'Tombstone';
1274 $data['id'] = $item['uri'];
1275 $data['type'] = $type;
1277 if ($item['deleted']) {
1281 $data['summary'] = BBCode::toPlaintext(BBCode::getAbstract($item['body'], Protocol::ACTIVITYPUB));
1283 if ($item['uri'] != $item['thr-parent']) {
1284 $data['inReplyTo'] = $item['thr-parent'];
1286 $data['inReplyTo'] = null;
1289 $data['diaspora:guid'] = $item['guid'];
1290 $data['published'] = DateTimeFormat::utc($item['created'] . '+00:00', DateTimeFormat::ATOM);
1292 if ($item['created'] != $item['edited']) {
1293 $data['updated'] = DateTimeFormat::utc($item['edited'] . '+00:00', DateTimeFormat::ATOM);
1296 $data['url'] = $item['plink'];
1297 $data['attributedTo'] = $item['author-link'];
1298 $data['sensitive'] = self::isSensitive($item['id']);
1299 $data['context'] = self::fetchContextURLForItem($item);
1301 if (!empty($item['title'])) {
1302 $data['name'] = BBCode::toPlaintext($item['title'], false);
1305 $permission_block = self::createPermissionBlockForItem($item, false);
1307 $body = $item['body'];
1309 if (empty($item['uid']) || !Feature::isEnabled($item['uid'], 'explicit_mentions')) {
1310 $body = self::prependMentions($body, $permission_block);
1313 if ($type == 'Note') {
1314 $body = self::removePictures($body);
1315 } elseif (($type == 'Article') && empty($data['summary'])) {
1316 $data['summary'] = BBCode::toPlaintext(Plaintext::shorten(self::removePictures($body), 1000));
1319 if ($type == 'Event') {
1320 $data = array_merge($data, self::createEvent($item));
1322 $regexp = "/[@!]\[url\=([^\[\]]*)\].*?\[\/url\]/ism";
1323 $body = preg_replace_callback($regexp, ['self', 'mentionCallback'], $body);
1325 $data['content'] = BBCode::convert($body, false, 9);
1328 // The regular "content" field does contain a minimized HTML. This is done since systems like
1329 // Mastodon has got problems with - for example - embedded pictures.
1330 // The contentMap does contain the unmodified HTML.
1331 $language = self::getLanguage($item);
1332 if (!empty($language)) {
1333 $regexp = "/[@!]\[url\=([^\[\]]*)\].*?\[\/url\]/ism";
1334 $richbody = preg_replace_callback($regexp, ['self', 'mentionCallback'], $item['body']);
1335 $richbody = BBCode::removeAttachment($richbody);
1337 $data['contentMap'][$language] = BBCode::convert($richbody, false);
1340 $data['source'] = ['content' => $item['body'], 'mediaType' => "text/bbcode"];
1342 if (!empty($item['signed_text']) && ($item['uri'] != $item['thr-parent'])) {
1343 $data['diaspora:comment'] = $item['signed_text'];
1346 $data['attachment'] = self::createAttachmentList($item, $type);
1347 $data['tag'] = self::createTagList($item);
1349 if (empty($data['location']) && (!empty($item['coord']) || !empty($item['location']))) {
1350 $data['location'] = self::createLocation($item);
1353 if (!empty($item['app'])) {
1354 $data['generator'] = ['type' => 'Application', 'name' => $item['app']];
1357 $data = array_merge($data, $permission_block);
1363 * Fetches the language from the post, the user or the system.
1365 * @param array $item
1367 * @return string language string
1369 private static function getLanguage(array $item)
1371 // Try to fetch the language from the post itself
1372 if (!empty($item['language'])) {
1373 $languages = array_keys(json_decode($item['language'], true));
1374 if (!empty($languages[0])) {
1375 return $languages[0];
1379 // Otherwise use the user's language
1380 if (!empty($item['uid'])) {
1381 $user = DBA::selectFirst('user', ['language'], ['uid' => $item['uid']]);
1382 if (!empty($user['language'])) {
1383 return $user['language'];
1387 // And finally just use the system language
1388 return DI::config()->get('system', 'language');
1392 * Creates an an "add tag" entry
1394 * @param array $item
1395 * @param array $data activity data
1397 * @return array with activity data for adding tags
1398 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1399 * @throws \ImagickException
1401 private static function createAddTag($item, $data)
1403 $object = XML::parseString($item['object'], false);
1404 $target = XML::parseString($item["target"], false);
1406 $data['diaspora:guid'] = $item['guid'];
1407 $data['actor'] = $item['author-link'];
1408 $data['target'] = (string)$target->id;
1409 $data['summary'] = BBCode::toPlaintext($item['body']);
1410 $data['object'] = ['id' => (string)$object->id, 'type' => 'tag', 'name' => (string)$object->title, 'content' => (string)$object->content];
1416 * Creates an announce object entry
1418 * @param array $item
1419 * @param array $data activity data
1421 * @return array with activity data
1422 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1423 * @throws \ImagickException
1425 private static function createAnnounce($item, $data)
1427 $orig_body = $item['body'];
1428 $announce = self::getAnnounceArray($item);
1429 if (empty($announce)) {
1430 $data['type'] = 'Create';
1431 $data['object'] = self::createNote($item);
1435 if (empty($announce['comment'])) {
1436 // Pure announce, without a quote
1437 $data['type'] = 'Announce';
1438 $data['object'] = $announce['object']['uri'];
1443 $data['type'] = 'Create';
1444 $item['body'] = $announce['comment'] . "\n" . $announce['object']['plink'];
1445 $data['object'] = self::createNote($item);
1447 /// @todo Finally descide how to implement this in AP. This is a possible way:
1448 $data['object']['attachment'][] = self::createNote($announce['object']);
1450 $data['object']['source']['content'] = $orig_body;
1455 * Return announce related data if the item is an annunce
1457 * @param array $item
1461 public static function getAnnounceArray($item)
1463 $reshared = Item::getShareArray($item);
1464 if (empty($reshared['guid'])) {
1468 $reshared_item = Item::selectFirst([], ['guid' => $reshared['guid']]);
1469 if (!DBA::isResult($reshared_item)) {
1473 if (!in_array($reshared_item['network'], [Protocol::ACTIVITYPUB, Protocol::DFRN])) {
1477 $profile = APContact::getByURL($reshared_item['author-link'], false);
1478 if (empty($profile)) {
1482 return ['object' => $reshared_item, 'actor' => $profile, 'comment' => $reshared['comment']];
1486 * Checks if the provided item array is an announce
1488 * @param array $item
1492 public static function isAnnounce($item)
1494 $announce = self::getAnnounceArray($item);
1495 if (empty($announce)) {
1499 return empty($announce['comment']);
1503 * Creates an activity id for a given contact id
1505 * @param integer $cid Contact ID of target
1507 * @return bool|string activity id
1509 public static function activityIDFromContact($cid)
1511 $contact = DBA::selectFirst('contact', ['uid', 'id', 'created'], ['id' => $cid]);
1512 if (!DBA::isResult($contact)) {
1516 $hash = hash('ripemd128', $contact['uid'].'-'.$contact['id'].'-'.$contact['created']);
1517 $uuid = substr($hash, 0, 8). '-' . substr($hash, 8, 4) . '-' . substr($hash, 12, 4) . '-' . substr($hash, 16, 4) . '-' . substr($hash, 20, 12);
1518 return DI::baseUrl() . '/activity/' . $uuid;
1522 * Transmits a contact suggestion to a given inbox
1524 * @param integer $uid User ID
1525 * @param string $inbox Target inbox
1526 * @param integer $suggestion_id Suggestion ID
1528 * @return boolean was the transmission successful?
1529 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1531 public static function sendContactSuggestion($uid, $inbox, $suggestion_id)
1533 $owner = User::getOwnerDataById($uid);
1535 $suggestion = DI::fsuggest()->getById($suggestion_id);
1537 $data = ['@context' => ActivityPub::CONTEXT,
1538 'id' => DI::baseUrl() . '/activity/' . System::createGUID(),
1539 'type' => 'Announce',
1540 'actor' => $owner['url'],
1541 'object' => $suggestion->url,
1542 'content' => $suggestion->note,
1543 'instrument' => self::getService(),
1544 'to' => [ActivityPub::PUBLIC_COLLECTION],
1547 $signed = LDSignature::sign($data, $owner);
1549 Logger::log('Deliver profile deletion for user ' . $uid . ' to ' . $inbox . ' via ActivityPub', Logger::DEBUG);
1550 return HTTPSignature::transmit($signed, $inbox, $uid);
1554 * Transmits a profile relocation to a given inbox
1556 * @param integer $uid User ID
1557 * @param string $inbox Target inbox
1559 * @return boolean was the transmission successful?
1560 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1562 public static function sendProfileRelocation($uid, $inbox)
1564 $owner = User::getOwnerDataById($uid);
1566 $data = ['@context' => ActivityPub::CONTEXT,
1567 'id' => DI::baseUrl() . '/activity/' . System::createGUID(),
1568 'type' => 'dfrn:relocate',
1569 'actor' => $owner['url'],
1570 'object' => $owner['url'],
1571 'published' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
1572 'instrument' => self::getService(),
1573 'to' => [ActivityPub::PUBLIC_COLLECTION],
1576 $signed = LDSignature::sign($data, $owner);
1578 Logger::log('Deliver profile relocation for user ' . $uid . ' to ' . $inbox . ' via ActivityPub', Logger::DEBUG);
1579 return HTTPSignature::transmit($signed, $inbox, $uid);
1583 * Transmits a profile deletion to a given inbox
1585 * @param integer $uid User ID
1586 * @param string $inbox Target inbox
1588 * @return boolean was the transmission successful?
1589 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1591 public static function sendProfileDeletion($uid, $inbox)
1593 $owner = User::getOwnerDataById($uid);
1595 if (empty($owner)) {
1596 Logger::error('No owner data found, the deletion message cannot be processed.', ['user' => $uid]);
1600 if (empty($owner['uprvkey'])) {
1601 Logger::error('No private key for owner found, the deletion message cannot be processed.', ['user' => $uid]);
1605 $data = ['@context' => ActivityPub::CONTEXT,
1606 'id' => DI::baseUrl() . '/activity/' . System::createGUID(),
1608 'actor' => $owner['url'],
1609 'object' => $owner['url'],
1610 'published' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
1611 'instrument' => self::getService(),
1612 'to' => [ActivityPub::PUBLIC_COLLECTION],
1615 $signed = LDSignature::sign($data, $owner);
1617 Logger::log('Deliver profile deletion for user ' . $uid . ' to ' . $inbox . ' via ActivityPub', Logger::DEBUG);
1618 return HTTPSignature::transmit($signed, $inbox, $uid);
1622 * Transmits a profile change to a given inbox
1624 * @param integer $uid User ID
1625 * @param string $inbox Target inbox
1627 * @return boolean was the transmission successful?
1628 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1629 * @throws \ImagickException
1631 public static function sendProfileUpdate($uid, $inbox)
1633 $owner = User::getOwnerDataById($uid);
1634 $profile = APContact::getByURL($owner['url']);
1636 $data = ['@context' => ActivityPub::CONTEXT,
1637 'id' => DI::baseUrl() . '/activity/' . System::createGUID(),
1639 'actor' => $owner['url'],
1640 'object' => self::getProfile($uid),
1641 'published' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
1642 'instrument' => self::getService(),
1643 'to' => [$profile['followers']],
1646 $signed = LDSignature::sign($data, $owner);
1648 Logger::log('Deliver profile update for user ' . $uid . ' to ' . $inbox . ' via ActivityPub', Logger::DEBUG);
1649 return HTTPSignature::transmit($signed, $inbox, $uid);
1653 * Transmits a given activity to a target
1655 * @param string $activity Type name
1656 * @param string $target Target profile
1657 * @param integer $uid User ID
1659 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1660 * @throws \ImagickException
1661 * @throws \Exception
1663 public static function sendActivity($activity, $target, $uid, $id = '')
1665 $profile = APContact::getByURL($target);
1666 if (empty($profile['inbox'])) {
1667 Logger::warning('No inbox found for target', ['target' => $target, 'profile' => $profile]);
1671 $owner = User::getOwnerDataById($uid);
1674 $id = DI::baseUrl() . '/activity/' . System::createGUID();
1677 $data = ['@context' => ActivityPub::CONTEXT,
1679 'type' => $activity,
1680 'actor' => $owner['url'],
1681 'object' => $profile['url'],
1682 'instrument' => self::getService(),
1683 'to' => [$profile['url']]];
1685 Logger::log('Sending activity ' . $activity . ' to ' . $target . ' for user ' . $uid, Logger::DEBUG);
1687 $signed = LDSignature::sign($data, $owner);
1688 return HTTPSignature::transmit($signed, $profile['inbox'], $uid);
1692 * Transmits a "follow object" activity to a target
1693 * This is a preparation for sending automated "follow" requests when receiving "Announce" messages
1695 * @param string $object Object URL
1696 * @param string $target Target profile
1697 * @param integer $uid User ID
1699 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1700 * @throws \ImagickException
1701 * @throws \Exception
1703 public static function sendFollowObject($object, $target, $uid = 0)
1705 $profile = APContact::getByURL($target);
1706 if (empty($profile['inbox'])) {
1707 Logger::warning('No inbox found for target', ['target' => $target, 'profile' => $profile]);
1712 // Fetch the list of administrators
1713 $admin_mail = explode(',', str_replace(' ', '', DI::config()->get('config', 'admin_email')));
1715 // We need to use some user as a sender. It doesn't care who it will send. We will use an administrator account.
1716 $condition = ['verified' => true, 'blocked' => false, 'account_removed' => false, 'account_expired' => false, 'email' => $admin_mail];
1717 $first_user = DBA::selectFirst('user', ['uid'], $condition);
1718 $uid = $first_user['uid'];
1721 $condition = ['verb' => Activity::FOLLOW, 'uid' => 0, 'parent-uri' => $object,
1722 'author-id' => Contact::getPublicIdByUserId($uid)];
1723 if (Item::exists($condition)) {
1724 Logger::log('Follow for ' . $object . ' for user ' . $uid . ' does already exist.', Logger::DEBUG);
1728 $owner = User::getOwnerDataById($uid);
1730 $data = ['@context' => ActivityPub::CONTEXT,
1731 'id' => DI::baseUrl() . '/activity/' . System::createGUID(),
1733 'actor' => $owner['url'],
1734 'object' => $object,
1735 'instrument' => self::getService(),
1736 'to' => [$profile['url']]];
1738 Logger::log('Sending follow ' . $object . ' to ' . $target . ' for user ' . $uid, Logger::DEBUG);
1740 $signed = LDSignature::sign($data, $owner);
1741 return HTTPSignature::transmit($signed, $profile['inbox'], $uid);
1745 * Transmit a message that the contact request had been accepted
1747 * @param string $target Target profile
1749 * @param integer $uid User ID
1750 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1751 * @throws \ImagickException
1753 public static function sendContactAccept($target, $id, $uid)
1755 $profile = APContact::getByURL($target);
1756 if (empty($profile['inbox'])) {
1757 Logger::warning('No inbox found for target', ['target' => $target, 'profile' => $profile]);
1761 $owner = User::getOwnerDataById($uid);
1762 $data = ['@context' => ActivityPub::CONTEXT,
1763 'id' => DI::baseUrl() . '/activity/' . System::createGUID(),
1765 'actor' => $owner['url'],
1767 'id' => (string)$id,
1769 'actor' => $profile['url'],
1770 'object' => $owner['url']
1772 'instrument' => self::getService(),
1773 'to' => [$profile['url']]];
1775 Logger::debug('Sending accept to ' . $target . ' for user ' . $uid . ' with id ' . $id);
1777 $signed = LDSignature::sign($data, $owner);
1778 HTTPSignature::transmit($signed, $profile['inbox'], $uid);
1782 * Reject a contact request or terminates the contact relation
1784 * @param string $target Target profile
1786 * @param integer $uid User ID
1787 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1788 * @throws \ImagickException
1790 public static function sendContactReject($target, $id, $uid)
1792 $profile = APContact::getByURL($target);
1793 if (empty($profile['inbox'])) {
1794 Logger::warning('No inbox found for target', ['target' => $target, 'profile' => $profile]);
1798 $owner = User::getOwnerDataById($uid);
1799 $data = ['@context' => ActivityPub::CONTEXT,
1800 'id' => DI::baseUrl() . '/activity/' . System::createGUID(),
1802 'actor' => $owner['url'],
1804 'id' => (string)$id,
1806 'actor' => $profile['url'],
1807 'object' => $owner['url']
1809 'instrument' => self::getService(),
1810 'to' => [$profile['url']]];
1812 Logger::debug('Sending reject to ' . $target . ' for user ' . $uid . ' with id ' . $id);
1814 $signed = LDSignature::sign($data, $owner);
1815 HTTPSignature::transmit($signed, $profile['inbox'], $uid);
1819 * Transmits a message that we don't want to follow this contact anymore
1821 * @param string $target Target profile
1822 * @param integer $uid User ID
1823 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1824 * @throws \ImagickException
1825 * @throws \Exception
1827 public static function sendContactUndo($target, $cid, $uid)
1829 $profile = APContact::getByURL($target);
1830 if (empty($profile['inbox'])) {
1831 Logger::warning('No inbox found for target', ['target' => $target, 'profile' => $profile]);
1835 $object_id = self::activityIDFromContact($cid);
1836 if (empty($object_id)) {
1840 $id = DI::baseUrl() . '/activity/' . System::createGUID();
1842 $owner = User::getOwnerDataById($uid);
1843 $data = ['@context' => ActivityPub::CONTEXT,
1846 'actor' => $owner['url'],
1847 'object' => ['id' => $object_id, 'type' => 'Follow',
1848 'actor' => $owner['url'],
1849 'object' => $profile['url']],
1850 'instrument' => self::getService(),
1851 'to' => [$profile['url']]];
1853 Logger::log('Sending undo to ' . $target . ' for user ' . $uid . ' with id ' . $id, Logger::DEBUG);
1855 $signed = LDSignature::sign($data, $owner);
1856 HTTPSignature::transmit($signed, $profile['inbox'], $uid);
1859 private static function prependMentions($body, array $permission_block)
1861 if (DI::config()->get('system', 'disable_implicit_mentions')) {
1867 foreach ($permission_block['to'] as $profile_url) {
1868 $profile = Contact::getDetailsByURL($profile_url);
1869 if (!empty($profile['addr'])
1870 && $profile['contact-type'] != Contact::TYPE_COMMUNITY
1871 && !strstr($body, $profile['addr'])
1872 && !strstr($body, $profile_url)
1874 $mentions[] = '@[url=' . $profile_url . ']' . $profile['nick'] . '[/url]';
1878 $mentions[] = $body;
1880 return implode(' ', $mentions);