3 * @copyright Copyright (C) 2020, Friendica
5 * @license GNU AGPL version 3 or any later version
7 * This program is free software: you can redistribute it and/or modify
8 * it under the terms of the GNU Affero General Public License as
9 * published by the Free Software Foundation, either version 3 of the
10 * License, or (at your option) any later version.
12 * This program is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU Affero General Public License for more details.
17 * You should have received a copy of the GNU Affero General Public License
18 * along with this program. If not, see <https://www.gnu.org/licenses/>.
22 namespace Friendica\Protocol\ActivityPub;
24 use Friendica\Content\Feature;
25 use Friendica\Content\Text\BBCode;
26 use Friendica\Content\Text\Plaintext;
27 use Friendica\Core\Cache\Duration;
28 use Friendica\Core\Logger;
29 use Friendica\Core\Protocol;
30 use Friendica\Core\System;
31 use Friendica\Database\DBA;
33 use Friendica\Model\APContact;
34 use Friendica\Model\Contact;
35 use Friendica\Model\Conversation;
36 use Friendica\Model\Item;
37 use Friendica\Model\ItemURI;
38 use Friendica\Model\Profile;
39 use Friendica\Model\Photo;
40 use Friendica\Model\Tag;
41 use Friendica\Model\User;
42 use Friendica\Protocol\Activity;
43 use Friendica\Protocol\ActivityPub;
44 use Friendica\Util\DateTimeFormat;
45 use Friendica\Util\HTTPSignature;
46 use Friendica\Util\Images;
47 use Friendica\Util\JsonLD;
48 use Friendica\Util\LDSignature;
49 use Friendica\Util\Map;
50 use Friendica\Util\Network;
51 use Friendica\Util\XML;
53 require_once 'include/api.php';
54 require_once 'mod/share.php';
57 * ActivityPub Transmitter Protocol class
65 * Add relay servers to the list of inboxes
67 * @param array $inboxes
68 * @return array inboxes with added relay servers
70 public static function addRelayServerInboxes(array $inboxes = [])
72 $contacts = DBA::select('apcontact', ['inbox'],
73 ["`type` = ? AND `url` IN (SELECT `url` FROM `contact` WHERE `uid` = ? AND `rel` IN (?, ?))",
74 'Application', 0, Contact::FOLLOWER, Contact::FRIEND]);
75 while ($contact = DBA::fetch($contacts)) {
76 $inboxes[] = $contact['inbox'];
78 DBA::close($contacts);
84 * Subscribe to a relay
86 * @param string $url Subscribe actor url
87 * @return bool success
89 public static function sendRelayFollow(string $url)
91 $contact = Contact::getByURL($url);
92 if (empty($contact)) {
96 $activity_id = ActivityPub\Transmitter::activityIDFromContact($contact['id']);
97 $success = ActivityPub\Transmitter::sendActivity('Follow', $url, 0, $activity_id);
99 $rel = $contact['rel'] == Contact::SHARING ? Contact::FRIEND : Contact::FOLLOWER;
100 DBA::update('contact', ['rel' => $rel], ['id' => $contact['id']]);
107 * Unsubscribe from a relay
109 * @param string $url Subscribe actor url
110 * @param bool $force Set the relay status as non follower even if unsubscribe hadn't worked
111 * @return bool success
113 public static function sendRelayUndoFollow(string $url, bool $force = false)
115 $contact = Contact::getByURL($url);
116 if (empty($contact)) {
120 $success = self::sendContactUndo($url, $contact['id'], 0);
121 if ($success || $force) {
122 $rel = $contact['rel'] == Contact::FRIEND ? Contact::SHARING : Contact::NOTHING;
123 DBA::update('contact', ['rel' => $rel], ['id' => $contact['id']]);
130 * Collects a list of contacts of the given owner
132 * @param array $owner Owner array
133 * @param int|array $rel The relevant value(s) contact.rel should match
134 * @param string $module The name of the relevant AP endpoint module (followers|following)
135 * @param integer $page Page number
137 * @return array of owners
140 public static function getContacts($owner, $rel, $module, $page = null)
144 'uid' => $owner['uid'],
151 $condition = DBA::buildCondition($parameters);
153 $sql = "SELECT COUNT(*) as `count`
155 JOIN `apcontact` ON `apcontact`.`url` = `contact`.`url`
158 $contacts = DBA::fetchFirst($sql, ...$parameters);
160 $modulePath = '/' . $module . '/';
162 $data = ['@context' => ActivityPub::CONTEXT];
163 $data['id'] = DI::baseUrl() . $modulePath . $owner['nickname'];
164 $data['type'] = 'OrderedCollection';
165 $data['totalItems'] = $contacts['count'];
167 // When we hide our friends we will only show the pure number but don't allow more.
168 $profile = Profile::getByUID($owner['uid']);
169 if (!empty($profile['hide-friends'])) {
174 $data['first'] = DI::baseUrl() . $modulePath . $owner['nickname'] . '?page=1';
176 $data['type'] = 'OrderedCollectionPage';
179 $sql = "SELECT `contact`.`url`
181 JOIN `apcontact` ON `apcontact`.`url` = `contact`.`url`
185 $parameters[] = ($page - 1) * 100;
188 $contacts = DBA::p($sql, ...$parameters);
189 while ($contact = DBA::fetch($contacts)) {
190 $list[] = $contact['url'];
192 DBA::close($contacts);
195 $data['next'] = DI::baseUrl() . $modulePath . $owner['nickname'] . '?page=' . ($page + 1);
198 $data['partOf'] = DI::baseUrl() . $modulePath . $owner['nickname'];
200 $data['orderedItems'] = $list;
207 * Public posts for the given owner
209 * @param array $owner Owner array
210 * @param integer $page Page number
211 * @param string $requester URL of requesting account
213 * @return array of posts
214 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
215 * @throws \ImagickException
217 public static function getOutbox($owner, $page = null, $requester = '')
219 $public_contact = Contact::getIdForURL($owner['url']);
220 $condition = ['uid' => 0, 'contact-id' => $public_contact,
221 'private' => [Item::PUBLIC, Item::UNLISTED]];
223 if (!empty($requester)) {
224 $requester_id = Contact::getIdForURL($requester, $owner['uid']);
225 if (!empty($requester_id)) {
226 $permissionSets = DI::permissionSet()->selectByContactId($requester_id, $owner['uid']);
227 if (!empty($permissionSets)) {
228 $condition = ['uid' => $owner['uid'], 'origin' => true,
229 'psid' => array_merge($permissionSets->column('id'),
230 [DI::permissionSet()->getIdFromACL($owner['uid'], '', '', '', '')])];
235 $condition = array_merge($condition,
236 ['author-id' => $public_contact,
237 'gravity' => [GRAVITY_PARENT, GRAVITY_COMMENT],
238 'deleted' => false, 'visible' => true, 'moderated' => false]);
240 $count = DBA::count('item', $condition);
242 $data = ['@context' => ActivityPub::CONTEXT];
243 $data['id'] = DI::baseUrl() . '/outbox/' . $owner['nickname'];
244 $data['type'] = 'OrderedCollection';
245 $data['totalItems'] = $count;
248 $data['first'] = DI::baseUrl() . '/outbox/' . $owner['nickname'] . '?page=1';
250 $data['type'] = 'OrderedCollectionPage';
253 $condition['parent-network'] = Protocol::NATIVE_SUPPORT;
255 $items = Item::select(['id'], $condition, ['limit' => [($page - 1) * 20, 20], 'order' => ['created' => true]]);
256 while ($item = Item::fetch($items)) {
257 $activity = self::createActivityFromItem($item['id'], true);
258 $activity['type'] = $activity['type'] == 'Update' ? 'Create' : $activity['type'];
260 // Only list "Create" activity objects here, no reshares
261 if (!empty($activity['object']) && ($activity['type'] == 'Create')) {
262 $list[] = $activity['object'];
267 $data['next'] = DI::baseUrl() . '/outbox/' . $owner['nickname'] . '?page=' . ($page + 1);
270 $data['partOf'] = DI::baseUrl() . '/outbox/' . $owner['nickname'];
272 $data['orderedItems'] = $list;
279 * Return the service array containing information the used software and it's url
281 * @return array with service data
283 private static function getService()
285 return ['type' => 'Service',
286 'name' => FRIENDICA_PLATFORM . " '" . FRIENDICA_CODENAME . "' " . FRIENDICA_VERSION . '-' . DB_UPDATE_VERSION,
287 'url' => DI::baseUrl()->get()];
291 * Return the ActivityPub profile of the given user
293 * @param integer $uid User ID
294 * @return array with profile data
295 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
297 public static function getProfile($uid)
300 $condition = ['uid' => $uid, 'blocked' => false, 'account_expired' => false,
301 'account_removed' => false, 'verified' => true];
302 $fields = ['guid', 'nickname', 'pubkey', 'account-type', 'page-flags'];
303 $user = DBA::selectFirst('user', $fields, $condition);
304 if (!DBA::isResult($user)) {
308 $fields = ['locality', 'region', 'country-name'];
309 $profile = DBA::selectFirst('profile', $fields, ['uid' => $uid]);
310 if (!DBA::isResult($profile)) {
314 $fields = ['name', 'url', 'location', 'about', 'avatar', 'photo'];
315 $contact = DBA::selectFirst('contact', $fields, ['uid' => $uid, 'self' => true]);
316 if (!DBA::isResult($contact)) {
320 $contact = User::getSystemAccount();
321 $user = ['guid' => '', 'nickname' => $contact['nick'], 'pubkey' => $contact['pubkey'],
322 'account-type' => $contact['contact-type'], 'page-flags' => User::PAGE_FLAGS_NORMAL];
323 $profile = ['locality' => '', 'region' => '', 'country-name' => ''];
326 $data = ['@context' => ActivityPub::CONTEXT];
327 $data['id'] = $contact['url'];
329 if (!empty($user['guid'])) {
330 $data['diaspora:guid'] = $user['guid'];
333 $data['type'] = ActivityPub::ACCOUNT_TYPES[$user['account-type']];
336 $data['following'] = DI::baseUrl() . '/following/' . $user['nickname'];
337 $data['followers'] = DI::baseUrl() . '/followers/' . $user['nickname'];
338 $data['inbox'] = DI::baseUrl() . '/inbox/' . $user['nickname'];
339 $data['outbox'] = DI::baseUrl() . '/outbox/' . $user['nickname'];
341 $data['inbox'] = DI::baseUrl() . '/friendica/inbox';
344 $data['preferredUsername'] = $user['nickname'];
345 $data['name'] = $contact['name'];
347 if (!empty($profile['country-name'] . $profile['region'] . $profile['locality'])) {
348 $data['vcard:hasAddress'] = ['@type' => 'vcard:Home', 'vcard:country-name' => $profile['country-name'],
349 'vcard:region' => $profile['region'], 'vcard:locality' => $profile['locality']];
352 if (!empty($contact['about'])) {
353 $data['summary'] = BBCode::convert($contact['about'], false);
356 $data['url'] = $contact['url'];
357 $data['manuallyApprovesFollowers'] = in_array($user['page-flags'], [User::PAGE_FLAGS_NORMAL, User::PAGE_FLAGS_PRVGROUP]);
358 $data['publicKey'] = ['id' => $contact['url'] . '#main-key',
359 'owner' => $contact['url'],
360 'publicKeyPem' => $user['pubkey']];
361 $data['endpoints'] = ['sharedInbox' => DI::baseUrl() . '/inbox'];
362 $data['icon'] = ['type' => 'Image',
363 'url' => $contact['photo']];
365 $data['generator'] = self::getService();
367 // tags: https://kitty.town/@inmysocks/100656097926961126.json
372 * @param string $username
374 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
376 public static function getDeletedUser($username)
379 '@context' => ActivityPub::CONTEXT,
380 'id' => DI::baseUrl() . '/profile/' . $username,
381 'type' => 'Tombstone',
382 'published' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
383 'updated' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
384 'deleted' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
389 * Returns an array with permissions of a given item array
393 * @return array with permissions
394 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
395 * @throws \ImagickException
397 private static function fetchPermissionBlockFromConversation($item)
399 if (empty($item['thr-parent'])) {
403 $condition = ['item-uri' => $item['thr-parent'], 'protocol' => Conversation::PARCEL_ACTIVITYPUB];
404 $conversation = DBA::selectFirst('conversation', ['source'], $condition);
405 if (!DBA::isResult($conversation)) {
409 $activity = json_decode($conversation['source'], true);
411 $actor = JsonLD::fetchElement($activity, 'actor', 'id');
412 $profile = APContact::getByURL($actor);
414 $item_profile = APContact::getByURL($item['author-link']);
415 $exclude[] = $item['author-link'];
417 if ($item['gravity'] == GRAVITY_PARENT) {
418 $exclude[] = $item['owner-link'];
421 $permissions['to'][] = $actor;
423 foreach (['to', 'cc', 'bto', 'bcc'] as $element) {
424 if (empty($activity[$element])) {
427 if (is_string($activity[$element])) {
428 $activity[$element] = [$activity[$element]];
431 foreach ($activity[$element] as $receiver) {
432 if (empty($receiver)) {
436 if (!empty($profile['followers']) && $receiver == $profile['followers'] && !empty($item_profile['followers'])) {
437 $permissions[$element][] = $item_profile['followers'];
438 } elseif (!in_array($receiver, $exclude)) {
439 $permissions[$element][] = $receiver;
447 * Creates an array of permissions from an item thread
449 * @param array $item Item array
450 * @param boolean $blindcopy addressing via "bcc" or "cc"?
451 * @param integer $last_id Last item id for adding receivers
452 * @param boolean $forum_mode "true" means that we are sending content to a forum
454 * @return array with permission data
455 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
456 * @throws \ImagickException
458 private static function createPermissionBlockForItem($item, $blindcopy, $last_id = 0, $forum_mode = false)
461 $last_id = $item['id'];
466 // Check if we should always deliver our stuff via BCC
467 if (!empty($item['uid'])) {
468 $profile = User::getOwnerDataById($item['uid']);
469 if (!empty($profile)) {
470 $always_bcc = $profile['hide-friends'];
474 if (DI::config()->get('system', 'ap_always_bcc')) {
478 if (self::isAnnounce($item) || DI::config()->get('debug', 'total_ap_delivery')) {
479 // Will be activated in a later step
480 $networks = Protocol::FEDERATED;
482 // For now only send to these contacts:
483 $networks = [Protocol::ACTIVITYPUB, Protocol::OSTATUS];
486 $data = ['to' => [], 'cc' => [], 'bcc' => []];
488 if ($item['gravity'] == GRAVITY_PARENT) {
489 $actor_profile = APContact::getByURL($item['owner-link']);
491 $actor_profile = APContact::getByURL($item['author-link']);
494 $terms = Tag::getByURIId($item['uri-id'], [Tag::MENTION, Tag::IMPLICIT_MENTION, Tag::EXCLUSIVE_MENTION]);
496 if ($item['private'] != Item::PRIVATE) {
497 // Directly mention the original author upon a quoted reshare.
498 // Else just ensure that the original author receives the reshare.
499 $announce = self::getAnnounceArray($item);
500 if (!empty($announce['comment'])) {
501 $data['to'][] = $announce['actor']['url'];
502 } elseif (!empty($announce)) {
503 $data['cc'][] = $announce['actor']['url'];
506 $data = array_merge($data, self::fetchPermissionBlockFromConversation($item));
508 // Check if the item is completely public or unlisted
509 if ($item['private'] == Item::PUBLIC) {
510 $data['to'][] = ActivityPub::PUBLIC_COLLECTION;
512 $data['cc'][] = ActivityPub::PUBLIC_COLLECTION;
515 foreach ($terms as $term) {
516 $profile = APContact::getByURL($term['url'], false);
517 if (!empty($profile)) {
518 $data['to'][] = $profile['url'];
522 $receiver_list = Item::enumeratePermissions($item, true);
524 foreach ($terms as $term) {
525 $cid = Contact::getIdForURL($term['url'], $item['uid']);
526 if (!empty($cid) && in_array($cid, $receiver_list)) {
527 $contact = DBA::selectFirst('contact', ['url', 'network', 'protocol'], ['id' => $cid]);
528 if (!DBA::isResult($contact) || (!in_array($contact['network'], $networks) && ($contact['protocol'] != Protocol::ACTIVITYPUB))) {
532 if (!empty($profile = APContact::getByURL($contact['url'], false))) {
533 $data['to'][] = $profile['url'];
538 foreach ($receiver_list as $receiver) {
539 $contact = DBA::selectFirst('contact', ['url', 'hidden', 'network', 'protocol'], ['id' => $receiver]);
540 if (!DBA::isResult($contact) || (!in_array($contact['network'], $networks) && ($contact['protocol'] != Protocol::ACTIVITYPUB))) {
544 if (!empty($profile = APContact::getByURL($contact['url'], false))) {
545 if ($contact['hidden'] || $always_bcc) {
546 $data['bcc'][] = $profile['url'];
548 $data['cc'][] = $profile['url'];
554 if (!empty($item['parent'])) {
555 $parents = Item::select(['id', 'author-link', 'owner-link', 'gravity', 'uri'], ['parent' => $item['parent']]);
556 while ($parent = Item::fetch($parents)) {
557 if ($parent['gravity'] == GRAVITY_PARENT) {
558 $profile = APContact::getByURL($parent['owner-link'], false);
559 if (!empty($profile)) {
560 if ($item['gravity'] != GRAVITY_PARENT) {
561 // Comments to forums are directed to the forum
562 // But comments to forums aren't directed to the followers collection
563 // This rule is only valid when the actor isn't the forum.
564 // The forum needs to transmit their content to their followers.
565 if (($profile['type'] == 'Group') && ($profile['url'] != $actor_profile['url'])) {
566 $data['to'][] = $profile['url'];
568 $data['cc'][] = $profile['url'];
569 if (($item['private'] != Item::PRIVATE) && !empty($actor_profile['followers'])) {
570 $data['cc'][] = $actor_profile['followers'];
574 // Public thread parent post always are directed to the followers
575 if (($item['private'] != Item::PRIVATE) && !$forum_mode) {
576 $data['cc'][] = $actor_profile['followers'];
582 // Don't include data from future posts
583 if ($parent['id'] >= $last_id) {
587 $profile = APContact::getByURL($parent['author-link'], false);
588 if (!empty($profile)) {
589 if (($profile['type'] == 'Group') || ($parent['uri'] == $item['thr-parent'])) {
590 $data['to'][] = $profile['url'];
592 $data['cc'][] = $profile['url'];
596 DBA::close($parents);
599 $data['to'] = array_unique($data['to']);
600 $data['cc'] = array_unique($data['cc']);
601 $data['bcc'] = array_unique($data['bcc']);
603 if (($key = array_search($item['author-link'], $data['to'])) !== false) {
604 unset($data['to'][$key]);
607 if (($key = array_search($item['author-link'], $data['cc'])) !== false) {
608 unset($data['cc'][$key]);
611 if (($key = array_search($item['author-link'], $data['bcc'])) !== false) {
612 unset($data['bcc'][$key]);
615 foreach ($data['to'] as $to) {
616 if (($key = array_search($to, $data['cc'])) !== false) {
617 unset($data['cc'][$key]);
620 if (($key = array_search($to, $data['bcc'])) !== false) {
621 unset($data['bcc'][$key]);
625 foreach ($data['cc'] as $cc) {
626 if (($key = array_search($cc, $data['bcc'])) !== false) {
627 unset($data['bcc'][$key]);
631 $receivers = ['to' => array_values($data['to']), 'cc' => array_values($data['cc']), 'bcc' => array_values($data['bcc'])];
634 unset($receivers['bcc']);
641 * Check if an inbox is archived
643 * @param string $url Inbox url
645 * @return boolean "true" if inbox is archived
647 private static function archivedInbox($url)
649 return DBA::exists('inbox-status', ['url' => $url, 'archive' => true]);
653 * Fetches a list of inboxes of followers of a given user
655 * @param integer $uid User ID
656 * @param boolean $personal fetch personal inboxes
658 * @return array of follower inboxes
659 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
660 * @throws \ImagickException
662 public static function fetchTargetInboxesforUser($uid, $personal = false)
668 if (!empty($item['uid'])) {
669 $profile = User::getOwnerDataById($item['uid']);
670 if (!empty($profile)) {
671 $isforum = $profile['account-type'] == User::ACCOUNT_TYPE_COMMUNITY;
675 if (DI::config()->get('debug', 'total_ap_delivery')) {
676 // Will be activated in a later step
677 $networks = Protocol::FEDERATED;
679 // For now only send to these contacts:
680 $networks = [Protocol::ACTIVITYPUB, Protocol::OSTATUS];
683 $condition = ['uid' => $uid, 'archive' => false, 'pending' => false];
686 $condition['rel'] = [Contact::FOLLOWER, Contact::FRIEND];
689 $contacts = DBA::select('contact', ['url', 'network', 'protocol'], $condition);
690 while ($contact = DBA::fetch($contacts)) {
691 if (Contact::isLocal($contact['url'])) {
695 if (!in_array($contact['network'], $networks) && ($contact['protocol'] != Protocol::ACTIVITYPUB)) {
699 if ($isforum && ($contact['dfrn'] == Protocol::DFRN)) {
703 if (Network::isUrlBlocked($contact['url'])) {
707 $profile = APContact::getByURL($contact['url'], false);
708 if (!empty($profile)) {
709 if (empty($profile['sharedinbox']) || $personal) {
710 $target = $profile['inbox'];
712 $target = $profile['sharedinbox'];
714 if (!self::archivedInbox($target)) {
715 $inboxes[$target] = $target;
719 DBA::close($contacts);
725 * Fetches an array of inboxes for the given item and user
727 * @param array $item Item array
728 * @param integer $uid User ID
729 * @param boolean $personal fetch personal inboxes
730 * @param integer $last_id Last item id for adding receivers
731 * @param boolean $forum_mode "true" means that we are sending content to a forum
732 * @return array with inboxes
733 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
734 * @throws \ImagickException
736 public static function fetchTargetInboxes($item, $uid, $personal = false, $last_id = 0, $forum_mode = false)
738 $permissions = self::createPermissionBlockForItem($item, true, $last_id, $forum_mode);
739 if (empty($permissions)) {
745 if ($item['gravity'] == GRAVITY_ACTIVITY) {
746 $item_profile = APContact::getByURL($item['author-link'], false);
748 $item_profile = APContact::getByURL($item['owner-link'], false);
751 if (empty($item_profile)) {
755 $profile_uid = User::getIdForURL($item_profile['url']);
757 foreach (['to', 'cc', 'bto', 'bcc'] as $element) {
758 if (empty($permissions[$element])) {
762 $blindcopy = in_array($element, ['bto', 'bcc']);
764 foreach ($permissions[$element] as $receiver) {
765 if (empty($receiver) || Network::isUrlBlocked($receiver)) {
769 if ($item_profile && ($receiver == $item_profile['followers']) && ($uid == $profile_uid)) {
770 $inboxes = array_merge($inboxes, self::fetchTargetInboxesforUser($uid, $personal));
772 if (Contact::isLocal($receiver)) {
776 $profile = APContact::getByURL($receiver, false);
777 if (!empty($profile)) {
778 if (empty($profile['sharedinbox']) || $personal || $blindcopy) {
779 $target = $profile['inbox'];
781 $target = $profile['sharedinbox'];
783 if (!self::archivedInbox($target)) {
784 $inboxes[$target] = $target;
795 * Creates an array in the structure of the item table for a given mail id
797 * @param integer $mail_id
802 public static function ItemArrayFromMail($mail_id)
804 $mail = DBA::selectFirst('mail', [], ['id' => $mail_id]);
805 if (!DBA::isResult($mail)) {
809 $mail['uri-id'] = ItemURI::insert(['uri' => $mail['uri'], 'guid' => $mail['guid']]);
811 $reply = DBA::selectFirst('mail', ['uri'], ['parent-uri' => $mail['parent-uri'], 'reply' => false]);
813 // Making the post more compatible for Mastodon by:
814 // - Making it a note and not an article (no title)
815 // - Moving the title into the "summary" field that is used as a "content warning"
816 $mail['body'] = '[abstract]' . $mail['title'] . "[/abstract]\n" . $mail['body'];
819 $mail['author-link'] = $mail['owner-link'] = $mail['from-url'];
820 $mail['allow_cid'] = '<'.$mail['contact-id'].'>';
821 $mail['allow_gid'] = '';
822 $mail['deny_cid'] = '';
823 $mail['deny_gid'] = '';
824 $mail['private'] = true;
825 $mail['deleted'] = false;
826 $mail['edited'] = $mail['created'];
827 $mail['plink'] = $mail['uri'];
828 $mail['thr-parent'] = $reply['uri'];
829 $mail['gravity'] = ($mail['reply'] ? GRAVITY_COMMENT: GRAVITY_PARENT);
831 $mail['event-type'] = '';
832 $mail['attach'] = '';
840 * Creates an activity array for a given mail id
842 * @param integer $mail_id
843 * @param boolean $object_mode Is the activity item is used inside another object?
845 * @return array of activity
848 public static function createActivityFromMail($mail_id, $object_mode = false)
850 $mail = self::ItemArrayFromMail($mail_id);
854 $object = self::createNote($mail);
857 $data = ['@context' => ActivityPub::CONTEXT];
862 $data['id'] = $mail['uri'] . '/Create';
863 $data['type'] = 'Create';
864 $data['actor'] = $mail['author-link'];
865 $data['published'] = DateTimeFormat::utc($mail['created'] . '+00:00', DateTimeFormat::ATOM);
866 $data['instrument'] = self::getService();
867 $data = array_merge($data, self::createPermissionBlockForItem($mail, true));
869 if (empty($data['to']) && !empty($data['cc'])) {
870 $data['to'] = $data['cc'];
873 if (empty($data['to']) && !empty($data['bcc'])) {
874 $data['to'] = $data['bcc'];
880 $object['to'] = $data['to'];
881 $object['tag'] = [['type' => 'Mention', 'href' => $object['to'][0], 'name' => '']];
883 unset($object['cc']);
884 unset($object['bcc']);
886 $data['directMessage'] = true;
888 $data['object'] = $object;
890 $owner = User::getOwnerDataById($mail['uid']);
892 if (!$object_mode && !empty($owner)) {
893 return LDSignature::sign($data, $owner);
900 * Returns the activity type of a given item
904 * @return string with activity type
905 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
906 * @throws \ImagickException
908 private static function getTypeOfItem($item)
912 // Only check for a reshare, if it is a real reshare and no quoted reshare
913 if (strpos($item['body'], "[share") === 0) {
914 $announce = self::getAnnounceArray($item);
915 $reshared = !empty($announce);
920 } elseif ($item['verb'] == Activity::POST) {
921 if ($item['created'] == $item['edited']) {
926 } elseif ($item['verb'] == Activity::LIKE) {
928 } elseif ($item['verb'] == Activity::DISLIKE) {
930 } elseif ($item['verb'] == Activity::ATTEND) {
932 } elseif ($item['verb'] == Activity::ATTENDNO) {
934 } elseif ($item['verb'] == Activity::ATTENDMAYBE) {
935 $type = 'TentativeAccept';
936 } elseif ($item['verb'] == Activity::FOLLOW) {
938 } elseif ($item['verb'] == Activity::TAG) {
940 } elseif ($item['verb'] == Activity::ANNOUNCE) {
950 * Creates the activity or fetches it from the cache
952 * @param integer $item_id
953 * @param boolean $force Force new cache entry
955 * @return array with the activity
958 public static function createCachedActivityFromItem($item_id, $force = false)
960 $cachekey = 'APDelivery:createActivity:' . $item_id;
963 $data = DI::cache()->get($cachekey);
964 if (!is_null($data)) {
969 $data = self::createActivityFromItem($item_id);
971 DI::cache()->set($cachekey, $data, Duration::QUARTER_HOUR);
976 * Creates an activity array for a given item id
978 * @param integer $item_id
979 * @param boolean $object_mode Is the activity item is used inside another object?
981 * @return array of activity
984 public static function createActivityFromItem($item_id, $object_mode = false)
986 Logger::info('Fetching activity', ['item' => $item_id]);
987 $item = Item::selectFirst([], ['id' => $item_id, 'parent-network' => Protocol::NATIVE_SUPPORT]);
988 if (!DBA::isResult($item)) {
992 // In case of a forum post ensure to return the original post if author and forum are on the same machine
993 if (!empty($item['forum_mode'])) {
994 $author = Contact::getById($item['author-id'], ['nurl']);
995 if (!empty($author['nurl'])) {
996 $self = Contact::selectFirst(['uid'], ['nurl' => $author['nurl'], 'self' => true]);
997 if (!empty($self['uid'])) {
998 $item = Item::selectFirst([], ['uri-id' => $item['uri-id'], 'uid' => $self['uid']]);
1004 $condition = ['item-uri' => $item['uri'], 'protocol' => Conversation::PARCEL_ACTIVITYPUB];
1005 $conversation = DBA::selectFirst('conversation', ['source'], $condition);
1006 if (DBA::isResult($conversation)) {
1007 $data = json_decode($conversation['source'], true);
1008 if (!empty($data['type'])) {
1009 if (in_array($data['type'], ['Create', 'Update'])) {
1011 unset($data['@context']);
1012 unset($data['signature']);
1014 Logger::info('Return stored conversation', ['item' => $item_id]);
1016 } elseif (in_array('as:' . $data['type'], Receiver::CONTENT_TYPES)) {
1017 if (!empty($data['@context'])) {
1018 $context = $data['@context'];
1019 unset($data['@context']);
1021 unset($data['actor']);
1027 $type = self::getTypeOfItem($item);
1030 if (!$object_mode) {
1031 $data = ['@context' => $context ?? ActivityPub::CONTEXT];
1033 if ($item['deleted'] && ($item['gravity'] == GRAVITY_ACTIVITY)) {
1035 } elseif ($item['deleted']) {
1042 if (($item['gravity'] == GRAVITY_ACTIVITY) && ($type != 'Undo')) {
1043 $data['id'] = $item['uri'];
1045 $data['id'] = $item['uri'] . '/' . $type;
1048 $data['type'] = $type;
1050 if (($type != 'Announce') || ($item['gravity'] != GRAVITY_PARENT)) {
1051 $data['actor'] = $item['author-link'];
1053 $data['actor'] = $item['owner-link'];
1056 $data['published'] = DateTimeFormat::utc($item['created'] . '+00:00', DateTimeFormat::ATOM);
1058 $data['instrument'] = self::getService();
1060 $data = array_merge($data, self::createPermissionBlockForItem($item, false));
1062 if (in_array($data['type'], ['Create', 'Update', 'Delete'])) {
1063 $data['object'] = $object ?? self::createNote($item);
1064 } elseif ($data['type'] == 'Add') {
1065 $data = self::createAddTag($item, $data);
1066 } elseif ($data['type'] == 'Announce') {
1067 if ($item['verb'] == ACTIVITY::ANNOUNCE) {
1068 $data['object'] = $item['thr-parent'];
1070 $data = self::createAnnounce($item, $data);
1072 } elseif ($data['type'] == 'Follow') {
1073 $data['object'] = $item['parent-uri'];
1074 } elseif ($data['type'] == 'Undo') {
1075 $data['object'] = self::createActivityFromItem($item_id, true);
1077 $data['diaspora:guid'] = $item['guid'];
1078 if (!empty($item['signed_text'])) {
1079 $data['diaspora:like'] = $item['signed_text'];
1081 $data['object'] = $item['thr-parent'];
1084 if (!empty($item['contact-uid'])) {
1085 $uid = $item['contact-uid'];
1087 $uid = $item['uid'];
1090 $owner = User::getOwnerDataById($uid);
1092 Logger::info('Fetched activity', ['item' => $item_id, 'uid' => $uid]);
1094 // We don't sign if we aren't the actor. This is important for relaying content especially for forums
1095 if (!$object_mode && !empty($owner) && ($data['actor'] == $owner['url'])) {
1096 return LDSignature::sign($data, $owner);
1101 /// @todo Create "conversation" entry
1105 * Creates a location entry for a given item array
1107 * @param array $item
1109 * @return array with location array
1111 private static function createLocation($item)
1113 $location = ['type' => 'Place'];
1115 if (!empty($item['location'])) {
1116 $location['name'] = $item['location'];
1121 if (empty($item['coord'])) {
1122 $coord = Map::getCoordinates($item['location']);
1124 $coords = explode(' ', $item['coord']);
1125 if (count($coords) == 2) {
1126 $coord = ['lat' => $coords[0], 'lon' => $coords[1]];
1130 if (!empty($coord['lat']) && !empty($coord['lon'])) {
1131 $location['latitude'] = $coord['lat'];
1132 $location['longitude'] = $coord['lon'];
1139 * Returns a tag array for a given item array
1141 * @param array $item
1143 * @return array of tags
1144 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1146 private static function createTagList($item)
1150 $terms = Tag::getByURIId($item['uri-id'], [Tag::HASHTAG, Tag::MENTION, Tag::IMPLICIT_MENTION, Tag::EXCLUSIVE_MENTION]);
1151 foreach ($terms as $term) {
1152 if ($term['type'] == Tag::HASHTAG) {
1153 $url = DI::baseUrl() . '/search?tag=' . urlencode($term['name']);
1154 $tags[] = ['type' => 'Hashtag', 'href' => $url, 'name' => '#' . $term['name']];
1156 $contact = Contact::getByURL($term['url'], false, ['addr']);
1157 if (empty($contact)) {
1160 if (!empty($contact['addr'])) {
1161 $mention = '@' . $contact['addr'];
1163 $mention = '@' . $term['url'];
1166 $tags[] = ['type' => 'Mention', 'href' => $term['url'], 'name' => $mention];
1170 $announce = self::getAnnounceArray($item);
1171 // Mention the original author upon commented reshares
1172 if (!empty($announce['comment'])) {
1173 $tags[] = ['type' => 'Mention', 'href' => $announce['actor']['url'], 'name' => '@' . $announce['actor']['addr']];
1180 * Adds attachment data to the JSON document
1182 * @param array $item Data of the item that is to be posted
1183 * @param string $type Object type
1185 * @return array with attachment data
1186 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1188 private static function createAttachmentList($item, $type)
1192 // Currently deactivated, since it creates side effects on Mastodon and Pleroma.
1193 // It will be reactivated, once this cleared.
1195 $attach_data = BBCode::getAttachmentData($item['body']);
1196 if (!empty($attach_data['url'])) {
1197 $attachment = ['type' => 'Page',
1198 'mediaType' => 'text/html',
1199 'url' => $attach_data['url']];
1201 if (!empty($attach_data['title'])) {
1202 $attachment['name'] = $attach_data['title'];
1205 if (!empty($attach_data['description'])) {
1206 $attachment['summary'] = $attach_data['description'];
1209 if (!empty($attach_data['image'])) {
1210 $imgdata = Images::getInfoFromURLCached($attach_data['image']);
1212 $attachment['icon'] = ['type' => 'Image',
1213 'mediaType' => $imgdata['mime'],
1214 'width' => $imgdata[0],
1215 'height' => $imgdata[1],
1216 'url' => $attach_data['image']];
1220 $attachments[] = $attachment;
1223 $arr = explode('[/attach],', $item['attach']);
1225 foreach ($arr as $r) {
1227 $cnt = preg_match('|\[attach\]href=\"(.*?)\" length=\"(.*?)\" type=\"(.*?)\" title=\"(.*?)\"|', $r, $matches);
1229 $attributes = ['type' => 'Document',
1230 'mediaType' => $matches[3],
1231 'url' => $matches[1],
1234 if (trim($matches[4]) != '') {
1235 $attributes['name'] = trim($matches[4]);
1238 $attachments[] = $attributes;
1243 if ($type != 'Note') {
1244 return $attachments;
1247 // Simplify image codes
1248 $body = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '[img]$3[/img]', $item['body']);
1250 // Grab all pictures without alternative descriptions and create attachments out of them
1251 if (preg_match_all("/\[img\]([^\[\]]*)\[\/img\]/Usi", $body, $pictures)) {
1252 foreach ($pictures[1] as $picture) {
1253 $imgdata = Images::getInfoFromURLCached($picture);
1255 $attachments[] = ['type' => 'Document',
1256 'mediaType' => $imgdata['mime'],
1263 // Grab all pictures with alternative description and create attachments out of them
1264 if (preg_match_all("/\[img=([^\[\]]*)\]([^\[\]]*)\[\/img\]/Usi", $body, $pictures, PREG_SET_ORDER)) {
1265 foreach ($pictures as $picture) {
1266 $imgdata = Images::getInfoFromURLCached($picture[1]);
1268 $attachments[] = ['type' => 'Document',
1269 'mediaType' => $imgdata['mime'],
1270 'url' => $picture[1],
1271 'name' => $picture[2]];
1276 return $attachments;
1280 * Callback function to replace a Friendica style mention in a mention that is used on AP
1282 * @param array $match Matching values for the callback
1283 * @return string Replaced mention
1284 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1286 private static function mentionCallback($match)
1288 if (empty($match[1])) {
1292 $data = Contact::getByURL($match[1], false, ['url', 'nick']);
1293 if (empty($data['nick'])) {
1297 return '@[url=' . $data['url'] . ']' . $data['nick'] . '[/url]';
1301 * Remove image elements since they are added as attachment
1303 * @param string $body
1305 * @return string with removed images
1307 private static function removePictures($body)
1309 // Simplify image codes
1310 $body = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '[img]$3[/img]', $body);
1311 $body = preg_replace("/\[img\=(.*?)\](.*?)\[\/img\]/ism", '[img]$1[/img]', $body);
1313 // Now remove local links
1314 $body = preg_replace_callback(
1315 '/\[url=([^\[\]]*)\]\[img\](.*)\[\/img\]\[\/url\]/Usi',
1317 // We remove the link when it is a link to a local photo page
1318 if (Photo::isLocalPage($match[1])) {
1321 // otherwise we just return the link
1322 return '[url]' . $match[1] . '[/url]';
1327 // Remove all pictures
1328 $body = preg_replace("/\[img\]([^\[\]]*)\[\/img\]/Usi", '', $body);
1334 * Fetches the "context" value for a givem item array from the "conversation" table
1336 * @param array $item
1338 * @return string with context url
1339 * @throws \Exception
1341 private static function fetchContextURLForItem($item)
1343 $conversation = DBA::selectFirst('conversation', ['conversation-href', 'conversation-uri'], ['item-uri' => $item['parent-uri']]);
1344 if (DBA::isResult($conversation) && !empty($conversation['conversation-href'])) {
1345 $context_uri = $conversation['conversation-href'];
1346 } elseif (DBA::isResult($conversation) && !empty($conversation['conversation-uri'])) {
1347 $context_uri = $conversation['conversation-uri'];
1349 $context_uri = $item['parent-uri'] . '#context';
1351 return $context_uri;
1355 * Returns if the post contains sensitive content ("nsfw")
1357 * @param integer $uri_id
1360 * @throws \Exception
1362 private static function isSensitive($uri_id)
1364 return DBA::exists('tag-view', ['uri-id' => $uri_id, 'name' => 'nsfw']);
1368 * Creates event data
1370 * @param array $item
1372 * @return array with the event data
1373 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1375 public static function createEvent($item)
1378 $event['name'] = $item['event-summary'];
1379 $event['content'] = BBCode::convert($item['event-desc'], false, BBCode::ACTIVITYPUB);
1380 $event['startTime'] = DateTimeFormat::utc($item['event-start'] . '+00:00', DateTimeFormat::ATOM);
1382 if (!$item['event-nofinish']) {
1383 $event['endTime'] = DateTimeFormat::utc($item['event-finish'] . '+00:00', DateTimeFormat::ATOM);
1386 if (!empty($item['event-location'])) {
1387 $item['location'] = $item['event-location'];
1388 $event['location'] = self::createLocation($item);
1395 * Creates a note/article object array
1397 * @param array $item
1399 * @return array with the object data
1400 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1401 * @throws \ImagickException
1403 public static function createNote($item)
1409 if ($item['event-type'] == 'event') {
1411 } elseif (!empty($item['title'])) {
1417 if ($item['deleted']) {
1418 $type = 'Tombstone';
1422 $data['id'] = $item['uri'];
1423 $data['type'] = $type;
1425 if ($item['deleted']) {
1429 $data['summary'] = BBCode::toPlaintext(BBCode::getAbstract($item['body'], Protocol::ACTIVITYPUB));
1431 if ($item['uri'] != $item['thr-parent']) {
1432 $data['inReplyTo'] = $item['thr-parent'];
1434 $data['inReplyTo'] = null;
1437 $data['diaspora:guid'] = $item['guid'];
1438 $data['published'] = DateTimeFormat::utc($item['created'] . '+00:00', DateTimeFormat::ATOM);
1440 if ($item['created'] != $item['edited']) {
1441 $data['updated'] = DateTimeFormat::utc($item['edited'] . '+00:00', DateTimeFormat::ATOM);
1444 $data['url'] = $item['plink'];
1445 $data['attributedTo'] = $item['author-link'];
1446 $data['sensitive'] = self::isSensitive($item['uri-id']);
1447 $data['context'] = self::fetchContextURLForItem($item);
1449 if (!empty($item['title'])) {
1450 $data['name'] = BBCode::toPlaintext($item['title'], false);
1453 $permission_block = self::createPermissionBlockForItem($item, false);
1455 $body = $item['body'];
1457 if (empty($item['uid']) || !Feature::isEnabled($item['uid'], 'explicit_mentions')) {
1458 $body = self::prependMentions($body, $item['uri-id']);
1461 if ($type == 'Note') {
1462 $body = self::removePictures($body);
1463 } elseif (($type == 'Article') && empty($data['summary'])) {
1464 $data['summary'] = BBCode::toPlaintext(Plaintext::shorten(self::removePictures($body), 1000));
1467 if ($type == 'Event') {
1468 $data = array_merge($data, self::createEvent($item));
1470 $regexp = "/[@!]\[url\=([^\[\]]*)\].*?\[\/url\]/ism";
1471 $body = preg_replace_callback($regexp, ['self', 'mentionCallback'], $body);
1473 $data['content'] = BBCode::convert($body, false, BBCode::ACTIVITYPUB);
1476 // The regular "content" field does contain a minimized HTML. This is done since systems like
1477 // Mastodon has got problems with - for example - embedded pictures.
1478 // The contentMap does contain the unmodified HTML.
1479 $language = self::getLanguage($item);
1480 if (!empty($language)) {
1481 $regexp = "/[@!]\[url\=([^\[\]]*)\].*?\[\/url\]/ism";
1482 $richbody = preg_replace_callback($regexp, ['self', 'mentionCallback'], $item['body']);
1483 $richbody = BBCode::removeAttachment($richbody);
1485 $data['contentMap'][$language] = BBCode::convert($richbody, false);
1488 $data['source'] = ['content' => $item['body'], 'mediaType' => "text/bbcode"];
1490 if (!empty($item['signed_text']) && ($item['uri'] != $item['thr-parent'])) {
1491 $data['diaspora:comment'] = $item['signed_text'];
1494 $data['attachment'] = self::createAttachmentList($item, $type);
1495 $data['tag'] = self::createTagList($item);
1497 if (empty($data['location']) && (!empty($item['coord']) || !empty($item['location']))) {
1498 $data['location'] = self::createLocation($item);
1501 if (!empty($item['app'])) {
1502 $data['generator'] = ['type' => 'Application', 'name' => $item['app']];
1505 $data = array_merge($data, $permission_block);
1511 * Fetches the language from the post, the user or the system.
1513 * @param array $item
1515 * @return string language string
1517 private static function getLanguage(array $item)
1519 // Try to fetch the language from the post itself
1520 if (!empty($item['language'])) {
1521 $languages = array_keys(json_decode($item['language'], true));
1522 if (!empty($languages[0])) {
1523 return $languages[0];
1527 // Otherwise use the user's language
1528 if (!empty($item['uid'])) {
1529 $user = DBA::selectFirst('user', ['language'], ['uid' => $item['uid']]);
1530 if (!empty($user['language'])) {
1531 return $user['language'];
1535 // And finally just use the system language
1536 return DI::config()->get('system', 'language');
1540 * Creates an an "add tag" entry
1542 * @param array $item
1543 * @param array $data activity data
1545 * @return array with activity data for adding tags
1546 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1547 * @throws \ImagickException
1549 private static function createAddTag($item, $data)
1551 $object = XML::parseString($item['object']);
1552 $target = XML::parseString($item["target"]);
1554 $data['diaspora:guid'] = $item['guid'];
1555 $data['actor'] = $item['author-link'];
1556 $data['target'] = (string)$target->id;
1557 $data['summary'] = BBCode::toPlaintext($item['body']);
1558 $data['object'] = ['id' => (string)$object->id, 'type' => 'tag', 'name' => (string)$object->title, 'content' => (string)$object->content];
1564 * Creates an announce object entry
1566 * @param array $item
1567 * @param array $data activity data
1569 * @return array with activity data
1570 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1571 * @throws \ImagickException
1573 private static function createAnnounce($item, $data)
1575 $orig_body = $item['body'];
1576 $announce = self::getAnnounceArray($item);
1577 if (empty($announce)) {
1578 $data['type'] = 'Create';
1579 $data['object'] = self::createNote($item);
1583 if (empty($announce['comment'])) {
1584 // Pure announce, without a quote
1585 $data['type'] = 'Announce';
1586 $data['object'] = $announce['object']['uri'];
1591 $data['type'] = 'Create';
1592 $item['body'] = $announce['comment'] . "\n" . $announce['object']['plink'];
1593 $data['object'] = self::createNote($item);
1595 /// @todo Finally descide how to implement this in AP. This is a possible way:
1596 $data['object']['attachment'][] = self::createNote($announce['object']);
1598 $data['object']['source']['content'] = $orig_body;
1603 * Return announce related data if the item is an annunce
1605 * @param array $item
1609 public static function getAnnounceArray($item)
1611 $reshared = Item::getShareArray($item);
1612 if (empty($reshared['guid'])) {
1616 $reshared_item = Item::selectFirst([], ['guid' => $reshared['guid']]);
1617 if (!DBA::isResult($reshared_item)) {
1621 if (!in_array($reshared_item['network'], [Protocol::ACTIVITYPUB, Protocol::DFRN])) {
1625 $profile = APContact::getByURL($reshared_item['author-link'], false);
1626 if (empty($profile)) {
1630 return ['object' => $reshared_item, 'actor' => $profile, 'comment' => $reshared['comment']];
1634 * Checks if the provided item array is an announce
1636 * @param array $item
1640 public static function isAnnounce($item)
1642 if (!empty($item['verb']) && ($item['verb'] == Activity::ANNOUNCE)) {
1646 $announce = self::getAnnounceArray($item);
1647 if (empty($announce)) {
1651 return empty($announce['comment']);
1655 * Creates an activity id for a given contact id
1657 * @param integer $cid Contact ID of target
1659 * @return bool|string activity id
1661 public static function activityIDFromContact($cid)
1663 $contact = DBA::selectFirst('contact', ['uid', 'id', 'created'], ['id' => $cid]);
1664 if (!DBA::isResult($contact)) {
1668 $hash = hash('ripemd128', $contact['uid'].'-'.$contact['id'].'-'.$contact['created']);
1669 $uuid = substr($hash, 0, 8). '-' . substr($hash, 8, 4) . '-' . substr($hash, 12, 4) . '-' . substr($hash, 16, 4) . '-' . substr($hash, 20, 12);
1670 return DI::baseUrl() . '/activity/' . $uuid;
1674 * Transmits a contact suggestion to a given inbox
1676 * @param integer $uid User ID
1677 * @param string $inbox Target inbox
1678 * @param integer $suggestion_id Suggestion ID
1680 * @return boolean was the transmission successful?
1681 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1683 public static function sendContactSuggestion($uid, $inbox, $suggestion_id)
1685 $owner = User::getOwnerDataById($uid);
1687 $suggestion = DI::fsuggest()->getById($suggestion_id);
1689 $data = ['@context' => ActivityPub::CONTEXT,
1690 'id' => DI::baseUrl() . '/activity/' . System::createGUID(),
1691 'type' => 'Announce',
1692 'actor' => $owner['url'],
1693 'object' => $suggestion->url,
1694 'content' => $suggestion->note,
1695 'instrument' => self::getService(),
1696 'to' => [ActivityPub::PUBLIC_COLLECTION],
1699 $signed = LDSignature::sign($data, $owner);
1701 Logger::log('Deliver profile deletion for user ' . $uid . ' to ' . $inbox . ' via ActivityPub', Logger::DEBUG);
1702 return HTTPSignature::transmit($signed, $inbox, $uid);
1706 * Transmits a profile relocation to a given inbox
1708 * @param integer $uid User ID
1709 * @param string $inbox Target inbox
1711 * @return boolean was the transmission successful?
1712 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1714 public static function sendProfileRelocation($uid, $inbox)
1716 $owner = User::getOwnerDataById($uid);
1718 $data = ['@context' => ActivityPub::CONTEXT,
1719 'id' => DI::baseUrl() . '/activity/' . System::createGUID(),
1720 'type' => 'dfrn:relocate',
1721 'actor' => $owner['url'],
1722 'object' => $owner['url'],
1723 'published' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
1724 'instrument' => self::getService(),
1725 'to' => [ActivityPub::PUBLIC_COLLECTION],
1728 $signed = LDSignature::sign($data, $owner);
1730 Logger::log('Deliver profile relocation for user ' . $uid . ' to ' . $inbox . ' via ActivityPub', Logger::DEBUG);
1731 return HTTPSignature::transmit($signed, $inbox, $uid);
1735 * Transmits a profile deletion to a given inbox
1737 * @param integer $uid User ID
1738 * @param string $inbox Target inbox
1740 * @return boolean was the transmission successful?
1741 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1743 public static function sendProfileDeletion($uid, $inbox)
1745 $owner = User::getOwnerDataById($uid);
1747 if (empty($owner)) {
1748 Logger::error('No owner data found, the deletion message cannot be processed.', ['user' => $uid]);
1752 if (empty($owner['uprvkey'])) {
1753 Logger::error('No private key for owner found, the deletion message cannot be processed.', ['user' => $uid]);
1757 $data = ['@context' => ActivityPub::CONTEXT,
1758 'id' => DI::baseUrl() . '/activity/' . System::createGUID(),
1760 'actor' => $owner['url'],
1761 'object' => $owner['url'],
1762 'published' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
1763 'instrument' => self::getService(),
1764 'to' => [ActivityPub::PUBLIC_COLLECTION],
1767 $signed = LDSignature::sign($data, $owner);
1769 Logger::log('Deliver profile deletion for user ' . $uid . ' to ' . $inbox . ' via ActivityPub', Logger::DEBUG);
1770 return HTTPSignature::transmit($signed, $inbox, $uid);
1774 * Transmits a profile change to a given inbox
1776 * @param integer $uid User ID
1777 * @param string $inbox Target inbox
1779 * @return boolean was the transmission successful?
1780 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1781 * @throws \ImagickException
1783 public static function sendProfileUpdate($uid, $inbox)
1785 $owner = User::getOwnerDataById($uid);
1786 $profile = APContact::getByURL($owner['url']);
1788 $data = ['@context' => ActivityPub::CONTEXT,
1789 'id' => DI::baseUrl() . '/activity/' . System::createGUID(),
1791 'actor' => $owner['url'],
1792 'object' => self::getProfile($uid),
1793 'published' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
1794 'instrument' => self::getService(),
1795 'to' => [$profile['followers']],
1798 $signed = LDSignature::sign($data, $owner);
1800 Logger::log('Deliver profile update for user ' . $uid . ' to ' . $inbox . ' via ActivityPub', Logger::DEBUG);
1801 return HTTPSignature::transmit($signed, $inbox, $uid);
1805 * Transmits a given activity to a target
1807 * @param string $activity Type name
1808 * @param string $target Target profile
1809 * @param integer $uid User ID
1811 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1812 * @throws \ImagickException
1813 * @throws \Exception
1815 public static function sendActivity($activity, $target, $uid, $id = '')
1817 $profile = APContact::getByURL($target);
1818 if (empty($profile['inbox'])) {
1819 Logger::warning('No inbox found for target', ['target' => $target, 'profile' => $profile]);
1823 $owner = User::getOwnerDataById($uid);
1826 $id = DI::baseUrl() . '/activity/' . System::createGUID();
1829 $data = ['@context' => ActivityPub::CONTEXT,
1831 'type' => $activity,
1832 'actor' => $owner['url'],
1833 'object' => $profile['url'],
1834 'instrument' => self::getService(),
1835 'to' => [$profile['url']]];
1837 Logger::log('Sending activity ' . $activity . ' to ' . $target . ' for user ' . $uid, Logger::DEBUG);
1839 $signed = LDSignature::sign($data, $owner);
1840 return HTTPSignature::transmit($signed, $profile['inbox'], $uid);
1844 * Transmits a "follow object" activity to a target
1845 * This is a preparation for sending automated "follow" requests when receiving "Announce" messages
1847 * @param string $object Object URL
1848 * @param string $target Target profile
1849 * @param integer $uid User ID
1851 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1852 * @throws \ImagickException
1853 * @throws \Exception
1855 public static function sendFollowObject($object, $target, $uid = 0)
1857 $profile = APContact::getByURL($target);
1858 if (empty($profile['inbox'])) {
1859 Logger::warning('No inbox found for target', ['target' => $target, 'profile' => $profile]);
1864 // Fetch the list of administrators
1865 $admin_mail = explode(',', str_replace(' ', '', DI::config()->get('config', 'admin_email')));
1867 // We need to use some user as a sender. It doesn't care who it will send. We will use an administrator account.
1868 $condition = ['verified' => true, 'blocked' => false, 'account_removed' => false, 'account_expired' => false, 'email' => $admin_mail];
1869 $first_user = DBA::selectFirst('user', ['uid'], $condition);
1870 $uid = $first_user['uid'];
1873 $condition = ['verb' => Activity::FOLLOW, 'uid' => 0, 'parent-uri' => $object,
1874 'author-id' => Contact::getPublicIdByUserId($uid)];
1875 if (Item::exists($condition)) {
1876 Logger::log('Follow for ' . $object . ' for user ' . $uid . ' does already exist.', Logger::DEBUG);
1880 $owner = User::getOwnerDataById($uid);
1882 $data = ['@context' => ActivityPub::CONTEXT,
1883 'id' => DI::baseUrl() . '/activity/' . System::createGUID(),
1885 'actor' => $owner['url'],
1886 'object' => $object,
1887 'instrument' => self::getService(),
1888 'to' => [$profile['url']]];
1890 Logger::log('Sending follow ' . $object . ' to ' . $target . ' for user ' . $uid, Logger::DEBUG);
1892 $signed = LDSignature::sign($data, $owner);
1893 return HTTPSignature::transmit($signed, $profile['inbox'], $uid);
1897 * Transmit a message that the contact request had been accepted
1899 * @param string $target Target profile
1901 * @param integer $uid User ID
1902 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1903 * @throws \ImagickException
1905 public static function sendContactAccept($target, $id, $uid)
1907 $profile = APContact::getByURL($target);
1908 if (empty($profile['inbox'])) {
1909 Logger::warning('No inbox found for target', ['target' => $target, 'profile' => $profile]);
1913 $owner = User::getOwnerDataById($uid);
1914 $data = ['@context' => ActivityPub::CONTEXT,
1915 'id' => DI::baseUrl() . '/activity/' . System::createGUID(),
1917 'actor' => $owner['url'],
1919 'id' => (string)$id,
1921 'actor' => $profile['url'],
1922 'object' => $owner['url']
1924 'instrument' => self::getService(),
1925 'to' => [$profile['url']]];
1927 Logger::debug('Sending accept to ' . $target . ' for user ' . $uid . ' with id ' . $id);
1929 $signed = LDSignature::sign($data, $owner);
1930 HTTPSignature::transmit($signed, $profile['inbox'], $uid);
1934 * Reject a contact request or terminates the contact relation
1936 * @param string $target Target profile
1938 * @param integer $uid User ID
1939 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1940 * @throws \ImagickException
1942 public static function sendContactReject($target, $id, $uid)
1944 $profile = APContact::getByURL($target);
1945 if (empty($profile['inbox'])) {
1946 Logger::warning('No inbox found for target', ['target' => $target, 'profile' => $profile]);
1950 $owner = User::getOwnerDataById($uid);
1951 $data = ['@context' => ActivityPub::CONTEXT,
1952 'id' => DI::baseUrl() . '/activity/' . System::createGUID(),
1954 'actor' => $owner['url'],
1956 'id' => (string)$id,
1958 'actor' => $profile['url'],
1959 'object' => $owner['url']
1961 'instrument' => self::getService(),
1962 'to' => [$profile['url']]];
1964 Logger::debug('Sending reject to ' . $target . ' for user ' . $uid . ' with id ' . $id);
1966 $signed = LDSignature::sign($data, $owner);
1967 HTTPSignature::transmit($signed, $profile['inbox'], $uid);
1971 * Transmits a message that we don't want to follow this contact anymore
1973 * @param string $target Target profile
1974 * @param integer $uid User ID
1975 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1976 * @throws \ImagickException
1977 * @throws \Exception
1978 * @return bool success
1980 public static function sendContactUndo($target, $cid, $uid)
1982 $profile = APContact::getByURL($target);
1983 if (empty($profile['inbox'])) {
1984 Logger::warning('No inbox found for target', ['target' => $target, 'profile' => $profile]);
1988 $object_id = self::activityIDFromContact($cid);
1989 if (empty($object_id)) {
1993 $id = DI::baseUrl() . '/activity/' . System::createGUID();
1995 $owner = User::getOwnerDataById($uid);
1996 $data = ['@context' => ActivityPub::CONTEXT,
1999 'actor' => $owner['url'],
2000 'object' => ['id' => $object_id, 'type' => 'Follow',
2001 'actor' => $owner['url'],
2002 'object' => $profile['url']],
2003 'instrument' => self::getService(),
2004 'to' => [$profile['url']]];
2006 Logger::log('Sending undo to ' . $target . ' for user ' . $uid . ' with id ' . $id, Logger::DEBUG);
2008 $signed = LDSignature::sign($data, $owner);
2009 return HTTPSignature::transmit($signed, $profile['inbox'], $uid);
2012 private static function prependMentions($body, int $uriid)
2016 foreach (Tag::getByURIId($uriid, [Tag::IMPLICIT_MENTION]) as $tag) {
2017 $profile = Contact::getByURL($tag['url'], false, ['addr', 'contact-type', 'nick']);
2018 if (!empty($profile['addr'])
2019 && $profile['contact-type'] != Contact::TYPE_COMMUNITY
2020 && !strstr($body, $profile['addr'])
2021 && !strstr($body, $tag['url'])
2023 $mentions[] = '@[url=' . $tag['url'] . ']' . $profile['nick'] . '[/url]';
2027 $mentions[] = $body;
2029 return implode(' ', $mentions);