3 * @copyright Copyright (C) 2020, Friendica
5 * @license GNU AGPL version 3 or any later version
7 * This program is free software: you can redistribute it and/or modify
8 * it under the terms of the GNU Affero General Public License as
9 * published by the Free Software Foundation, either version 3 of the
10 * License, or (at your option) any later version.
12 * This program is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU Affero General Public License for more details.
17 * You should have received a copy of the GNU Affero General Public License
18 * along with this program. If not, see <https://www.gnu.org/licenses/>.
22 namespace Friendica\Protocol\ActivityPub;
24 use Friendica\Content\Feature;
25 use Friendica\Content\Text\BBCode;
26 use Friendica\Content\Text\Plaintext;
27 use Friendica\Core\Cache\Duration;
28 use Friendica\Core\Logger;
29 use Friendica\Core\Protocol;
30 use Friendica\Core\System;
31 use Friendica\Database\DBA;
33 use Friendica\Model\APContact;
34 use Friendica\Model\Contact;
35 use Friendica\Model\Conversation;
36 use Friendica\Model\Item;
37 use Friendica\Model\ItemURI;
38 use Friendica\Model\Profile;
39 use Friendica\Model\Photo;
40 use Friendica\Model\Tag;
41 use Friendica\Model\User;
42 use Friendica\Protocol\Activity;
43 use Friendica\Protocol\ActivityPub;
44 use Friendica\Util\DateTimeFormat;
45 use Friendica\Util\HTTPSignature;
46 use Friendica\Util\Images;
47 use Friendica\Util\JsonLD;
48 use Friendica\Util\LDSignature;
49 use Friendica\Util\Map;
50 use Friendica\Util\Network;
51 use Friendica\Util\XML;
53 require_once 'include/api.php';
54 require_once 'mod/share.php';
57 * ActivityPub Transmitter Protocol class
65 * Collects a list of contacts of the given owner
67 * @param array $owner Owner array
68 * @param int|array $rel The relevant value(s) contact.rel should match
69 * @param string $module The name of the relevant AP endpoint module (followers|following)
70 * @param integer $page Page number
72 * @return array of owners
75 public static function getContacts($owner, $rel, $module, $page = null)
79 'uid' => $owner['uid'],
86 $condition = DBA::buildCondition($parameters);
88 $sql = "SELECT COUNT(*) as `count`
90 JOIN `apcontact` ON `apcontact`.`url` = `contact`.`url`
93 $contacts = DBA::fetchFirst($sql, ...$parameters);
95 $modulePath = '/' . $module . '/';
97 $data = ['@context' => ActivityPub::CONTEXT];
98 $data['id'] = DI::baseUrl() . $modulePath . $owner['nickname'];
99 $data['type'] = 'OrderedCollection';
100 $data['totalItems'] = $contacts['count'];
102 // When we hide our friends we will only show the pure number but don't allow more.
103 $profile = Profile::getByUID($owner['uid']);
104 if (!empty($profile['hide-friends'])) {
109 $data['first'] = DI::baseUrl() . $modulePath . $owner['nickname'] . '?page=1';
111 $data['type'] = 'OrderedCollectionPage';
114 $sql = "SELECT `contact`.`url`
116 JOIN `apcontact` ON `apcontact`.`url` = `contact`.`url`
120 $parameters[] = ($page - 1) * 100;
123 $contacts = DBA::p($sql, ...$parameters);
124 while ($contact = DBA::fetch($contacts)) {
125 $list[] = $contact['url'];
127 DBA::close($contacts);
130 $data['next'] = DI::baseUrl() . $modulePath . $owner['nickname'] . '?page=' . ($page + 1);
133 $data['partOf'] = DI::baseUrl() . $modulePath . $owner['nickname'];
135 $data['orderedItems'] = $list;
142 * Public posts for the given owner
144 * @param array $owner Owner array
145 * @param integer $page Page numbe
147 * @return array of posts
148 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
149 * @throws \ImagickException
151 public static function getOutbox($owner, $page = null)
153 $public_contact = Contact::getIdForURL($owner['url']);
155 $condition = ['uid' => 0, 'contact-id' => $public_contact, 'author-id' => $public_contact,
156 'private' => [Item::PUBLIC, Item::UNLISTED], 'gravity' => [GRAVITY_PARENT, GRAVITY_COMMENT],
157 'deleted' => false, 'visible' => true, 'moderated' => false];
158 $count = DBA::count('item', $condition);
160 $data = ['@context' => ActivityPub::CONTEXT];
161 $data['id'] = DI::baseUrl() . '/outbox/' . $owner['nickname'];
162 $data['type'] = 'OrderedCollection';
163 $data['totalItems'] = $count;
166 $data['first'] = DI::baseUrl() . '/outbox/' . $owner['nickname'] . '?page=1';
168 $data['type'] = 'OrderedCollectionPage';
171 $condition['parent-network'] = Protocol::NATIVE_SUPPORT;
173 $items = Item::select(['id'], $condition, ['limit' => [($page - 1) * 20, 20], 'order' => ['created' => true]]);
174 while ($item = Item::fetch($items)) {
175 $activity = self::createActivityFromItem($item['id'], true);
176 $activity['type'] = $activity['type'] == 'Update' ? 'Create' : $activity['type'];
178 // Only list "Create" activity objects here, no reshares
179 if (!empty($activity['object']) && ($activity['type'] == 'Create')) {
180 $list[] = $activity['object'];
185 $data['next'] = DI::baseUrl() . '/outbox/' . $owner['nickname'] . '?page=' . ($page + 1);
188 $data['partOf'] = DI::baseUrl() . '/outbox/' . $owner['nickname'];
190 $data['orderedItems'] = $list;
197 * Return the service array containing information the used software and it's url
199 * @return array with service data
201 private static function getService()
203 return ['type' => 'Service',
204 'name' => FRIENDICA_PLATFORM . " '" . FRIENDICA_CODENAME . "' " . FRIENDICA_VERSION . '-' . DB_UPDATE_VERSION,
205 'url' => DI::baseUrl()->get()];
209 * Return the ActivityPub profile of the given user
211 * @param integer $uid User ID
212 * @return array with profile data
213 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
215 public static function getProfile($uid)
218 $condition = ['uid' => $uid, 'blocked' => false, 'account_expired' => false,
219 'account_removed' => false, 'verified' => true];
220 $fields = ['guid', 'nickname', 'pubkey', 'account-type', 'page-flags'];
221 $user = DBA::selectFirst('user', $fields, $condition);
222 if (!DBA::isResult($user)) {
226 $fields = ['locality', 'region', 'country-name'];
227 $profile = DBA::selectFirst('profile', $fields, ['uid' => $uid]);
228 if (!DBA::isResult($profile)) {
232 $fields = ['name', 'url', 'location', 'about', 'avatar', 'photo'];
233 $contact = DBA::selectFirst('contact', $fields, ['uid' => $uid, 'self' => true]);
234 if (!DBA::isResult($contact)) {
238 $contact = User::getSystemAccount();
239 $user = ['guid' => '', 'nickname' => $contact['nick'], 'pubkey' => $contact['pubkey'],
240 'account-type' => $contact['contact-type'], 'page-flags' => User::PAGE_FLAGS_NORMAL];
241 $profile = ['locality' => '', 'region' => '', 'country-name' => ''];
244 $data = ['@context' => ActivityPub::CONTEXT];
245 $data['id'] = $contact['url'];
247 if (!empty($user['guid'])) {
248 $data['diaspora:guid'] = $user['guid'];
251 $data['type'] = ActivityPub::ACCOUNT_TYPES[$user['account-type']];
254 $data['following'] = DI::baseUrl() . '/following/' . $user['nickname'];
255 $data['followers'] = DI::baseUrl() . '/followers/' . $user['nickname'];
256 $data['inbox'] = DI::baseUrl() . '/inbox/' . $user['nickname'];
257 $data['outbox'] = DI::baseUrl() . '/outbox/' . $user['nickname'];
259 $data['inbox'] = DI::baseUrl() . '/friendica/inbox';
262 $data['preferredUsername'] = $user['nickname'];
263 $data['name'] = $contact['name'];
265 if (!empty($profile['country-name'] . $profile['region'] . $profile['locality'])) {
266 $data['vcard:hasAddress'] = ['@type' => 'vcard:Home', 'vcard:country-name' => $profile['country-name'],
267 'vcard:region' => $profile['region'], 'vcard:locality' => $profile['locality']];
270 if (!empty($contact['about'])) {
271 $data['summary'] = BBCode::convert($contact['about'], false);
274 $data['url'] = $contact['url'];
275 $data['manuallyApprovesFollowers'] = in_array($user['page-flags'], [User::PAGE_FLAGS_NORMAL, User::PAGE_FLAGS_PRVGROUP]);
276 $data['publicKey'] = ['id' => $contact['url'] . '#main-key',
277 'owner' => $contact['url'],
278 'publicKeyPem' => $user['pubkey']];
279 $data['endpoints'] = ['sharedInbox' => DI::baseUrl() . '/inbox'];
280 $data['icon'] = ['type' => 'Image',
281 'url' => $contact['photo']];
283 $data['generator'] = self::getService();
285 // tags: https://kitty.town/@inmysocks/100656097926961126.json
290 * @param string $username
292 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
294 public static function getDeletedUser($username)
297 '@context' => ActivityPub::CONTEXT,
298 'id' => DI::baseUrl() . '/profile/' . $username,
299 'type' => 'Tombstone',
300 'published' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
301 'updated' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
302 'deleted' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
307 * Returns an array with permissions of a given item array
311 * @return array with permissions
312 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
313 * @throws \ImagickException
315 private static function fetchPermissionBlockFromConversation($item)
317 if (empty($item['thr-parent'])) {
321 $condition = ['item-uri' => $item['thr-parent'], 'protocol' => Conversation::PARCEL_ACTIVITYPUB];
322 $conversation = DBA::selectFirst('conversation', ['source'], $condition);
323 if (!DBA::isResult($conversation)) {
327 $activity = json_decode($conversation['source'], true);
329 $actor = JsonLD::fetchElement($activity, 'actor', 'id');
330 $profile = APContact::getByURL($actor);
332 $item_profile = APContact::getByURL($item['author-link']);
333 $exclude[] = $item['author-link'];
335 if ($item['gravity'] == GRAVITY_PARENT) {
336 $exclude[] = $item['owner-link'];
339 $permissions['to'][] = $actor;
341 foreach (['to', 'cc', 'bto', 'bcc'] as $element) {
342 if (empty($activity[$element])) {
345 if (is_string($activity[$element])) {
346 $activity[$element] = [$activity[$element]];
349 foreach ($activity[$element] as $receiver) {
350 if (empty($receiver)) {
354 if (!empty($profile['followers']) && $receiver == $profile['followers'] && !empty($item_profile['followers'])) {
355 $permissions[$element][] = $item_profile['followers'];
356 } elseif (!in_array($receiver, $exclude)) {
357 $permissions[$element][] = $receiver;
365 * Creates an array of permissions from an item thread
367 * @param array $item Item array
368 * @param boolean $blindcopy addressing via "bcc" or "cc"?
369 * @param integer $last_id Last item id for adding receivers
370 * @param boolean $forum_mode "true" means that we are sending content to a forum
372 * @return array with permission data
373 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
374 * @throws \ImagickException
376 private static function createPermissionBlockForItem($item, $blindcopy, $last_id = 0, $forum_mode = false)
379 $last_id = $item['id'];
385 // Check if we should always deliver our stuff via BCC
386 if (!empty($item['uid'])) {
387 $profile = User::getOwnerDataById($item['uid']);
388 if (!empty($profile)) {
389 $always_bcc = $profile['hide-friends'];
390 $isforum = $profile['account-type'] == User::ACCOUNT_TYPE_COMMUNITY;
394 if (DI::config()->get('system', 'ap_always_bcc')) {
398 if ((self::isAnnounce($item) && !$isforum) || DI::config()->get('debug', 'total_ap_delivery')) {
399 // Will be activated in a later step
400 $networks = Protocol::FEDERATED;
402 // For now only send to these contacts:
403 $networks = [Protocol::ACTIVITYPUB, Protocol::OSTATUS];
406 $data = ['to' => [], 'cc' => [], 'bcc' => []];
408 if ($item['gravity'] == GRAVITY_PARENT) {
409 $actor_profile = APContact::getByURL($item['owner-link']);
411 $actor_profile = APContact::getByURL($item['author-link']);
414 $terms = Tag::getByURIId($item['uri-id'], [Tag::MENTION, Tag::IMPLICIT_MENTION, Tag::EXCLUSIVE_MENTION]);
416 if ($item['private'] != Item::PRIVATE) {
417 // Directly mention the original author upon a quoted reshare.
418 // Else just ensure that the original author receives the reshare.
419 $announce = self::getAnnounceArray($item);
420 if (!empty($announce['comment'])) {
421 $data['to'][] = $announce['actor']['url'];
422 } elseif (!empty($announce)) {
423 $data['cc'][] = $announce['actor']['url'];
426 $data = array_merge($data, self::fetchPermissionBlockFromConversation($item));
428 // Check if the item is completely public or unlisted
429 if ($item['private'] == Item::PUBLIC) {
430 $data['to'][] = ActivityPub::PUBLIC_COLLECTION;
432 $data['cc'][] = ActivityPub::PUBLIC_COLLECTION;
435 foreach ($terms as $term) {
436 $profile = APContact::getByURL($term['url'], false);
437 if (!empty($profile)) {
438 $data['to'][] = $profile['url'];
442 $receiver_list = Item::enumeratePermissions($item, true);
444 foreach ($terms as $term) {
445 $cid = Contact::getIdForURL($term['url'], $item['uid']);
446 if (!empty($cid) && in_array($cid, $receiver_list)) {
447 $contact = DBA::selectFirst('contact', ['url', 'network', 'protocol'], ['id' => $cid]);
448 if (!DBA::isResult($contact) || (!in_array($contact['network'], $networks) && ($contact['protocol'] != Protocol::ACTIVITYPUB))) {
452 if ($isforum && DBA::isResult($contact) && ($contact['dfrn'] == Protocol::DFRN)) {
456 if (!empty($profile = APContact::getByURL($contact['url'], false))) {
457 $data['to'][] = $profile['url'];
462 foreach ($receiver_list as $receiver) {
463 $contact = DBA::selectFirst('contact', ['url', 'hidden', 'network', 'protocol'], ['id' => $receiver]);
464 if (!DBA::isResult($contact) || (!in_array($contact['network'], $networks) && ($contact['protocol'] != Protocol::ACTIVITYPUB))) {
468 if ($isforum && DBA::isResult($contact) && ($contact['dfrn'] == Protocol::DFRN)) {
472 if (!empty($profile = APContact::getByURL($contact['url'], false))) {
473 if ($contact['hidden'] || $always_bcc) {
474 $data['bcc'][] = $profile['url'];
476 $data['cc'][] = $profile['url'];
482 if (!empty($item['parent'])) {
483 $parents = Item::select(['id', 'author-link', 'owner-link', 'gravity', 'uri'], ['parent' => $item['parent']]);
484 while ($parent = Item::fetch($parents)) {
485 if ($parent['gravity'] == GRAVITY_PARENT) {
486 $profile = APContact::getByURL($parent['owner-link'], false);
487 if (!empty($profile)) {
488 if ($item['gravity'] != GRAVITY_PARENT) {
489 // Comments to forums are directed to the forum
490 // But comments to forums aren't directed to the followers collection
491 // This rule is only valid when the actor isn't the forum.
492 // The forum needs to transmit their content to their followers.
493 if (($profile['type'] == 'Group') && ($profile['url'] != $actor_profile['url'])) {
494 $data['to'][] = $profile['url'];
496 $data['cc'][] = $profile['url'];
497 if (($item['private'] != Item::PRIVATE) && !empty($actor_profile['followers'])) {
498 $data['cc'][] = $actor_profile['followers'];
502 // Public thread parent post always are directed to the followers
503 if (($item['private'] != Item::PRIVATE) && !$forum_mode) {
504 $data['cc'][] = $actor_profile['followers'];
510 // Don't include data from future posts
511 if ($parent['id'] >= $last_id) {
515 $profile = APContact::getByURL($parent['author-link'], false);
516 if (!empty($profile)) {
517 if (($profile['type'] == 'Group') || ($parent['uri'] == $item['thr-parent'])) {
518 $data['to'][] = $profile['url'];
520 $data['cc'][] = $profile['url'];
524 DBA::close($parents);
527 $data['to'] = array_unique($data['to']);
528 $data['cc'] = array_unique($data['cc']);
529 $data['bcc'] = array_unique($data['bcc']);
531 if (($key = array_search($item['author-link'], $data['to'])) !== false) {
532 unset($data['to'][$key]);
535 if (($key = array_search($item['author-link'], $data['cc'])) !== false) {
536 unset($data['cc'][$key]);
539 if (($key = array_search($item['author-link'], $data['bcc'])) !== false) {
540 unset($data['bcc'][$key]);
543 foreach ($data['to'] as $to) {
544 if (($key = array_search($to, $data['cc'])) !== false) {
545 unset($data['cc'][$key]);
548 if (($key = array_search($to, $data['bcc'])) !== false) {
549 unset($data['bcc'][$key]);
553 foreach ($data['cc'] as $cc) {
554 if (($key = array_search($cc, $data['bcc'])) !== false) {
555 unset($data['bcc'][$key]);
559 $receivers = ['to' => array_values($data['to']), 'cc' => array_values($data['cc']), 'bcc' => array_values($data['bcc'])];
562 unset($receivers['bcc']);
569 * Check if an inbox is archived
571 * @param string $url Inbox url
573 * @return boolean "true" if inbox is archived
575 private static function archivedInbox($url)
577 return DBA::exists('inbox-status', ['url' => $url, 'archive' => true]);
581 * Fetches a list of inboxes of followers of a given user
583 * @param integer $uid User ID
584 * @param boolean $personal fetch personal inboxes
586 * @return array of follower inboxes
587 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
588 * @throws \ImagickException
590 public static function fetchTargetInboxesforUser($uid, $personal = false)
596 if (!empty($item['uid'])) {
597 $profile = User::getOwnerDataById($item['uid']);
598 if (!empty($profile)) {
599 $isforum = $profile['account-type'] == User::ACCOUNT_TYPE_COMMUNITY;
603 if (DI::config()->get('debug', 'total_ap_delivery')) {
604 // Will be activated in a later step
605 $networks = Protocol::FEDERATED;
607 // For now only send to these contacts:
608 $networks = [Protocol::ACTIVITYPUB, Protocol::OSTATUS];
611 $condition = ['uid' => $uid, 'archive' => false, 'pending' => false];
614 $condition['rel'] = [Contact::FOLLOWER, Contact::FRIEND];
617 $contacts = DBA::select('contact', ['url', 'network', 'protocol'], $condition);
618 while ($contact = DBA::fetch($contacts)) {
619 if (Contact::isLocal($contact['url'])) {
623 if (!in_array($contact['network'], $networks) && ($contact['protocol'] != Protocol::ACTIVITYPUB)) {
627 if ($isforum && ($contact['dfrn'] == Protocol::DFRN)) {
631 if (Network::isUrlBlocked($contact['url'])) {
635 $profile = APContact::getByURL($contact['url'], false);
636 if (!empty($profile)) {
637 if (empty($profile['sharedinbox']) || $personal) {
638 $target = $profile['inbox'];
640 $target = $profile['sharedinbox'];
642 if (!self::archivedInbox($target)) {
643 $inboxes[$target] = $target;
647 DBA::close($contacts);
653 * Fetches an array of inboxes for the given item and user
655 * @param array $item Item array
656 * @param integer $uid User ID
657 * @param boolean $personal fetch personal inboxes
658 * @param integer $last_id Last item id for adding receivers
659 * @param boolean $forum_mode "true" means that we are sending content to a forum
660 * @return array with inboxes
661 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
662 * @throws \ImagickException
664 public static function fetchTargetInboxes($item, $uid, $personal = false, $last_id = 0, $forum_mode = false)
666 $permissions = self::createPermissionBlockForItem($item, true, $last_id, $forum_mode);
667 if (empty($permissions)) {
673 if ($item['gravity'] == GRAVITY_ACTIVITY) {
674 $item_profile = APContact::getByURL($item['author-link'], false);
676 $item_profile = APContact::getByURL($item['owner-link'], false);
679 if (empty($item_profile)) {
683 $profile_uid = User::getIdForURL($item_profile['url']);
685 foreach (['to', 'cc', 'bto', 'bcc'] as $element) {
686 if (empty($permissions[$element])) {
690 $blindcopy = in_array($element, ['bto', 'bcc']);
692 foreach ($permissions[$element] as $receiver) {
693 if (empty($receiver) || Network::isUrlBlocked($receiver)) {
697 if ($item_profile && ($receiver == $item_profile['followers']) && ($uid == $profile_uid)) {
698 $inboxes = array_merge($inboxes, self::fetchTargetInboxesforUser($uid, $personal));
700 if (Contact::isLocal($receiver)) {
704 $profile = APContact::getByURL($receiver, false);
705 if (!empty($profile)) {
706 if (empty($profile['sharedinbox']) || $personal || $blindcopy) {
707 $target = $profile['inbox'];
709 $target = $profile['sharedinbox'];
711 if (!self::archivedInbox($target)) {
712 $inboxes[$target] = $target;
723 * Creates an array in the structure of the item table for a given mail id
725 * @param integer $mail_id
730 public static function ItemArrayFromMail($mail_id)
732 $mail = DBA::selectFirst('mail', [], ['id' => $mail_id]);
733 if (!DBA::isResult($mail)) {
737 $mail['uri-id'] = ItemURI::insert(['uri' => $mail['uri'], 'guid' => $mail['guid']]);
739 $reply = DBA::selectFirst('mail', ['uri'], ['parent-uri' => $mail['parent-uri'], 'reply' => false]);
741 // Making the post more compatible for Mastodon by:
742 // - Making it a note and not an article (no title)
743 // - Moving the title into the "summary" field that is used as a "content warning"
744 $mail['body'] = '[abstract]' . $mail['title'] . "[/abstract]\n" . $mail['body'];
747 $mail['author-link'] = $mail['owner-link'] = $mail['from-url'];
748 $mail['allow_cid'] = '<'.$mail['contact-id'].'>';
749 $mail['allow_gid'] = '';
750 $mail['deny_cid'] = '';
751 $mail['deny_gid'] = '';
752 $mail['private'] = true;
753 $mail['deleted'] = false;
754 $mail['edited'] = $mail['created'];
755 $mail['plink'] = $mail['uri'];
756 $mail['thr-parent'] = $reply['uri'];
757 $mail['gravity'] = ($mail['reply'] ? GRAVITY_COMMENT: GRAVITY_PARENT);
759 $mail['event-type'] = '';
760 $mail['attach'] = '';
768 * Creates an activity array for a given mail id
770 * @param integer $mail_id
771 * @param boolean $object_mode Is the activity item is used inside another object?
773 * @return array of activity
776 public static function createActivityFromMail($mail_id, $object_mode = false)
778 $mail = self::ItemArrayFromMail($mail_id);
779 $object = self::createNote($mail);
782 $data = ['@context' => ActivityPub::CONTEXT];
787 $data['id'] = $mail['uri'] . '/Create';
788 $data['type'] = 'Create';
789 $data['actor'] = $mail['author-link'];
790 $data['published'] = DateTimeFormat::utc($mail['created'] . '+00:00', DateTimeFormat::ATOM);
791 $data['instrument'] = self::getService();
792 $data = array_merge($data, self::createPermissionBlockForItem($mail, true));
794 if (empty($data['to']) && !empty($data['cc'])) {
795 $data['to'] = $data['cc'];
798 if (empty($data['to']) && !empty($data['bcc'])) {
799 $data['to'] = $data['bcc'];
805 $object['to'] = $data['to'];
806 $object['tag'] = [['type' => 'Mention', 'href' => $object['to'][0], 'name' => '']];
808 unset($object['cc']);
809 unset($object['bcc']);
811 $data['directMessage'] = true;
813 $data['object'] = $object;
815 $owner = User::getOwnerDataById($mail['uid']);
817 if (!$object_mode && !empty($owner)) {
818 return LDSignature::sign($data, $owner);
825 * Returns the activity type of a given item
829 * @return string with activity type
830 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
831 * @throws \ImagickException
833 private static function getTypeOfItem($item)
837 // Only check for a reshare, if it is a real reshare and no quoted reshare
838 if (strpos($item['body'], "[share") === 0) {
839 $announce = self::getAnnounceArray($item);
840 $reshared = !empty($announce);
845 } elseif ($item['verb'] == Activity::POST) {
846 if ($item['created'] == $item['edited']) {
851 } elseif ($item['verb'] == Activity::LIKE) {
853 } elseif ($item['verb'] == Activity::DISLIKE) {
855 } elseif ($item['verb'] == Activity::ATTEND) {
857 } elseif ($item['verb'] == Activity::ATTENDNO) {
859 } elseif ($item['verb'] == Activity::ATTENDMAYBE) {
860 $type = 'TentativeAccept';
861 } elseif ($item['verb'] == Activity::FOLLOW) {
863 } elseif ($item['verb'] == Activity::TAG) {
865 } elseif ($item['verb'] == Activity::ANNOUNCE) {
875 * Creates the activity or fetches it from the cache
877 * @param integer $item_id
878 * @param boolean $force Force new cache entry
880 * @return array with the activity
883 public static function createCachedActivityFromItem($item_id, $force = false)
885 $cachekey = 'APDelivery:createActivity:' . $item_id;
888 $data = DI::cache()->get($cachekey);
889 if (!is_null($data)) {
894 $data = self::createActivityFromItem($item_id);
896 DI::cache()->set($cachekey, $data, Duration::QUARTER_HOUR);
901 * Creates an activity array for a given item id
903 * @param integer $item_id
904 * @param boolean $object_mode Is the activity item is used inside another object?
906 * @return array of activity
909 public static function createActivityFromItem($item_id, $object_mode = false)
911 Logger::info('Fetching activity', ['item' => $item_id]);
912 $item = Item::selectFirst([], ['id' => $item_id, 'parent-network' => Protocol::NATIVE_SUPPORT]);
913 if (!DBA::isResult($item)) {
917 /// @todo This code should be removed by the end of the year 2020
918 if ($item['wall'] && ($item['uri'] == $item['parent-uri'])) {
919 $owner = User::getOwnerDataById($item['uid']);
920 if (($owner['account-type'] == User::ACCOUNT_TYPE_COMMUNITY) && ($item['author-link'] != $owner['url'])) {
923 // Disguise forum posts as reshares. Will later be converted to a real announce
924 $item['body'] = BBCode::getShareOpeningTag($item['author-name'], $item['author-link'], $item['author-avatar'],
925 $item['plink'], $item['created'], $item['guid']) . $item['body'] . '[/share]';
930 /// @todo This code should be activated by the end of the year 2020
931 // See also "tagDeliver";
932 // In case of a forum post ensure to return the original post if author and forum are on the same machine
933 if (!empty($item['forum_mode'])) {
934 $author = Contact::getById($item['author-id'], ['nurl']);
935 if (!empty($author['nurl'])) {
936 $self = Contact::selectFirst(['uid'], ['nurl' => $author['nurl'], 'self' => true]);
937 if (!empty($self['uid'])) {
938 $item = Item::selectFirst([], ['uri-id' => $item['uri-id'], 'uid' => $self['uid']]);
945 $condition = ['item-uri' => $item['uri'], 'protocol' => Conversation::PARCEL_ACTIVITYPUB];
946 $conversation = DBA::selectFirst('conversation', ['source'], $condition);
947 if (DBA::isResult($conversation)) {
948 $data = json_decode($conversation['source'], true);
949 if (!empty($data['type'])) {
950 if (in_array($data['type'], ['Create', 'Update'])) {
952 unset($data['@context']);
953 unset($data['signature']);
955 Logger::info('Return stored conversation', ['item' => $item_id]);
957 } elseif (in_array('as:' . $data['type'], Receiver::CONTENT_TYPES)) {
958 if (!empty($data['@context'])) {
959 $context = $data['@context'];
960 unset($data['@context']);
962 unset($data['actor']);
968 $type = self::getTypeOfItem($item);
972 $data = ['@context' => $context ?? ActivityPub::CONTEXT];
974 if ($item['deleted'] && ($item['gravity'] == GRAVITY_ACTIVITY)) {
976 } elseif ($item['deleted']) {
983 $data['id'] = $item['uri'] . '/' . $type;
984 $data['type'] = $type;
986 if (($type != 'Announce') || ($item['gravity'] != GRAVITY_PARENT)) {
987 $data['actor'] = $item['author-link'];
989 $data['actor'] = $item['owner-link'];
992 $data['published'] = DateTimeFormat::utc($item['created'] . '+00:00', DateTimeFormat::ATOM);
994 $data['instrument'] = self::getService();
996 $data = array_merge($data, self::createPermissionBlockForItem($item, false));
998 if (in_array($data['type'], ['Create', 'Update', 'Delete'])) {
999 $data['object'] = $object ?? self::createNote($item);
1000 } elseif ($data['type'] == 'Add') {
1001 $data = self::createAddTag($item, $data);
1002 } elseif ($data['type'] == 'Announce') {
1003 if ($item['verb'] == ACTIVITY::ANNOUNCE) {
1004 $data['object'] = $item['thr-parent'];
1006 $data = self::createAnnounce($item, $data);
1008 } elseif ($data['type'] == 'Follow') {
1009 $data['object'] = $item['parent-uri'];
1010 } elseif ($data['type'] == 'Undo') {
1011 $data['object'] = self::createActivityFromItem($item_id, true);
1013 $data['diaspora:guid'] = $item['guid'];
1014 if (!empty($item['signed_text'])) {
1015 $data['diaspora:like'] = $item['signed_text'];
1017 $data['object'] = $item['thr-parent'];
1020 if (!empty($item['contact-uid'])) {
1021 $uid = $item['contact-uid'];
1023 $uid = $item['uid'];
1026 $owner = User::getOwnerDataById($uid);
1028 Logger::info('Fetched activity', ['item' => $item_id, 'uid' => $uid]);
1030 // We don't sign if we aren't the actor. This is important for relaying content especially for forums
1031 if (!$object_mode && !empty($owner) && ($data['actor'] == $owner['url'])) {
1032 return LDSignature::sign($data, $owner);
1037 /// @todo Create "conversation" entry
1041 * Creates a location entry for a given item array
1043 * @param array $item
1045 * @return array with location array
1047 private static function createLocation($item)
1049 $location = ['type' => 'Place'];
1051 if (!empty($item['location'])) {
1052 $location['name'] = $item['location'];
1057 if (empty($item['coord'])) {
1058 $coord = Map::getCoordinates($item['location']);
1060 $coords = explode(' ', $item['coord']);
1061 if (count($coords) == 2) {
1062 $coord = ['lat' => $coords[0], 'lon' => $coords[1]];
1066 if (!empty($coord['lat']) && !empty($coord['lon'])) {
1067 $location['latitude'] = $coord['lat'];
1068 $location['longitude'] = $coord['lon'];
1075 * Returns a tag array for a given item array
1077 * @param array $item
1079 * @return array of tags
1080 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1082 private static function createTagList($item)
1086 $terms = Tag::getByURIId($item['uri-id'], [Tag::HASHTAG, Tag::MENTION, Tag::IMPLICIT_MENTION, Tag::EXCLUSIVE_MENTION]);
1087 foreach ($terms as $term) {
1088 if ($term['type'] == Tag::HASHTAG) {
1089 $url = DI::baseUrl() . '/search?tag=' . urlencode($term['name']);
1090 $tags[] = ['type' => 'Hashtag', 'href' => $url, 'name' => '#' . $term['name']];
1092 $contact = Contact::getByURL($term['url'], false, ['addr']);
1093 if (empty($contact)) {
1096 if (!empty($contact['addr'])) {
1097 $mention = '@' . $contact['addr'];
1099 $mention = '@' . $term['url'];
1102 $tags[] = ['type' => 'Mention', 'href' => $term['url'], 'name' => $mention];
1106 $announce = self::getAnnounceArray($item);
1107 // Mention the original author upon commented reshares
1108 if (!empty($announce['comment'])) {
1109 $tags[] = ['type' => 'Mention', 'href' => $announce['actor']['url'], 'name' => '@' . $announce['actor']['addr']];
1116 * Adds attachment data to the JSON document
1118 * @param array $item Data of the item that is to be posted
1119 * @param string $type Object type
1121 * @return array with attachment data
1122 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1124 private static function createAttachmentList($item, $type)
1128 // Currently deactivated, since it creates side effects on Mastodon and Pleroma.
1129 // It will be reactivated, once this cleared.
1131 $attach_data = BBCode::getAttachmentData($item['body']);
1132 if (!empty($attach_data['url'])) {
1133 $attachment = ['type' => 'Page',
1134 'mediaType' => 'text/html',
1135 'url' => $attach_data['url']];
1137 if (!empty($attach_data['title'])) {
1138 $attachment['name'] = $attach_data['title'];
1141 if (!empty($attach_data['description'])) {
1142 $attachment['summary'] = $attach_data['description'];
1145 if (!empty($attach_data['image'])) {
1146 $imgdata = Images::getInfoFromURLCached($attach_data['image']);
1148 $attachment['icon'] = ['type' => 'Image',
1149 'mediaType' => $imgdata['mime'],
1150 'width' => $imgdata[0],
1151 'height' => $imgdata[1],
1152 'url' => $attach_data['image']];
1156 $attachments[] = $attachment;
1159 $arr = explode('[/attach],', $item['attach']);
1161 foreach ($arr as $r) {
1163 $cnt = preg_match('|\[attach\]href=\"(.*?)\" length=\"(.*?)\" type=\"(.*?)\" title=\"(.*?)\"|', $r, $matches);
1165 $attributes = ['type' => 'Document',
1166 'mediaType' => $matches[3],
1167 'url' => $matches[1],
1170 if (trim($matches[4]) != '') {
1171 $attributes['name'] = trim($matches[4]);
1174 $attachments[] = $attributes;
1179 if ($type != 'Note') {
1180 return $attachments;
1183 // Simplify image codes
1184 $body = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '[img]$3[/img]', $item['body']);
1186 // Grab all pictures without alternative descriptions and create attachments out of them
1187 if (preg_match_all("/\[img\]([^\[\]]*)\[\/img\]/Usi", $body, $pictures)) {
1188 foreach ($pictures[1] as $picture) {
1189 $imgdata = Images::getInfoFromURLCached($picture);
1191 $attachments[] = ['type' => 'Document',
1192 'mediaType' => $imgdata['mime'],
1199 // Grab all pictures with alternative description and create attachments out of them
1200 if (preg_match_all("/\[img=([^\[\]]*)\]([^\[\]]*)\[\/img\]/Usi", $body, $pictures, PREG_SET_ORDER)) {
1201 foreach ($pictures as $picture) {
1202 $imgdata = Images::getInfoFromURLCached($picture[1]);
1204 $attachments[] = ['type' => 'Document',
1205 'mediaType' => $imgdata['mime'],
1206 'url' => $picture[1],
1207 'name' => $picture[2]];
1212 return $attachments;
1216 * Callback function to replace a Friendica style mention in a mention that is used on AP
1218 * @param array $match Matching values for the callback
1219 * @return string Replaced mention
1220 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1222 private static function mentionCallback($match)
1224 if (empty($match[1])) {
1228 $data = Contact::getByURL($match[1], false, ['url', 'nick']);
1229 if (empty($data['nick'])) {
1233 return '@[url=' . $data['url'] . ']' . $data['nick'] . '[/url]';
1237 * Remove image elements since they are added as attachment
1239 * @param string $body
1241 * @return string with removed images
1243 private static function removePictures($body)
1245 // Simplify image codes
1246 $body = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '[img]$3[/img]', $body);
1247 $body = preg_replace("/\[img\=(.*?)\](.*?)\[\/img\]/ism", '[img]$1[/img]', $body);
1249 // Now remove local links
1250 $body = preg_replace_callback(
1251 '/\[url=([^\[\]]*)\]\[img\](.*)\[\/img\]\[\/url\]/Usi',
1253 // We remove the link when it is a link to a local photo page
1254 if (Photo::isLocalPage($match[1])) {
1257 // otherwise we just return the link
1258 return '[url]' . $match[1] . '[/url]';
1263 // Remove all pictures
1264 $body = preg_replace("/\[img\]([^\[\]]*)\[\/img\]/Usi", '', $body);
1270 * Fetches the "context" value for a givem item array from the "conversation" table
1272 * @param array $item
1274 * @return string with context url
1275 * @throws \Exception
1277 private static function fetchContextURLForItem($item)
1279 $conversation = DBA::selectFirst('conversation', ['conversation-href', 'conversation-uri'], ['item-uri' => $item['parent-uri']]);
1280 if (DBA::isResult($conversation) && !empty($conversation['conversation-href'])) {
1281 $context_uri = $conversation['conversation-href'];
1282 } elseif (DBA::isResult($conversation) && !empty($conversation['conversation-uri'])) {
1283 $context_uri = $conversation['conversation-uri'];
1285 $context_uri = $item['parent-uri'] . '#context';
1287 return $context_uri;
1291 * Returns if the post contains sensitive content ("nsfw")
1293 * @param integer $uri_id
1296 * @throws \Exception
1298 private static function isSensitive($uri_id)
1300 return DBA::exists('tag-view', ['uri-id' => $uri_id, 'name' => 'nsfw']);
1304 * Creates event data
1306 * @param array $item
1308 * @return array with the event data
1309 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1311 public static function createEvent($item)
1314 $event['name'] = $item['event-summary'];
1315 $event['content'] = BBCode::convert($item['event-desc'], false, BBCode::ACTIVITYPUB);
1316 $event['startTime'] = DateTimeFormat::utc($item['event-start'] . '+00:00', DateTimeFormat::ATOM);
1318 if (!$item['event-nofinish']) {
1319 $event['endTime'] = DateTimeFormat::utc($item['event-finish'] . '+00:00', DateTimeFormat::ATOM);
1322 if (!empty($item['event-location'])) {
1323 $item['location'] = $item['event-location'];
1324 $event['location'] = self::createLocation($item);
1331 * Creates a note/article object array
1333 * @param array $item
1335 * @return array with the object data
1336 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1337 * @throws \ImagickException
1339 public static function createNote($item)
1345 if ($item['event-type'] == 'event') {
1347 } elseif (!empty($item['title'])) {
1353 if ($item['deleted']) {
1354 $type = 'Tombstone';
1358 $data['id'] = $item['uri'];
1359 $data['type'] = $type;
1361 if ($item['deleted']) {
1365 $data['summary'] = BBCode::toPlaintext(BBCode::getAbstract($item['body'], Protocol::ACTIVITYPUB));
1367 if ($item['uri'] != $item['thr-parent']) {
1368 $data['inReplyTo'] = $item['thr-parent'];
1370 $data['inReplyTo'] = null;
1373 $data['diaspora:guid'] = $item['guid'];
1374 $data['published'] = DateTimeFormat::utc($item['created'] . '+00:00', DateTimeFormat::ATOM);
1376 if ($item['created'] != $item['edited']) {
1377 $data['updated'] = DateTimeFormat::utc($item['edited'] . '+00:00', DateTimeFormat::ATOM);
1380 $data['url'] = $item['plink'];
1381 $data['attributedTo'] = $item['author-link'];
1382 $data['sensitive'] = self::isSensitive($item['uri-id']);
1383 $data['context'] = self::fetchContextURLForItem($item);
1385 if (!empty($item['title'])) {
1386 $data['name'] = BBCode::toPlaintext($item['title'], false);
1389 $permission_block = self::createPermissionBlockForItem($item, false);
1391 $body = $item['body'];
1393 if (empty($item['uid']) || !Feature::isEnabled($item['uid'], 'explicit_mentions')) {
1394 $body = self::prependMentions($body, $item['uri-id']);
1397 if ($type == 'Note') {
1398 $body = self::removePictures($body);
1399 } elseif (($type == 'Article') && empty($data['summary'])) {
1400 $data['summary'] = BBCode::toPlaintext(Plaintext::shorten(self::removePictures($body), 1000));
1403 if ($type == 'Event') {
1404 $data = array_merge($data, self::createEvent($item));
1406 $regexp = "/[@!]\[url\=([^\[\]]*)\].*?\[\/url\]/ism";
1407 $body = preg_replace_callback($regexp, ['self', 'mentionCallback'], $body);
1409 $data['content'] = BBCode::convert($body, false, BBCode::ACTIVITYPUB);
1412 // The regular "content" field does contain a minimized HTML. This is done since systems like
1413 // Mastodon has got problems with - for example - embedded pictures.
1414 // The contentMap does contain the unmodified HTML.
1415 $language = self::getLanguage($item);
1416 if (!empty($language)) {
1417 $regexp = "/[@!]\[url\=([^\[\]]*)\].*?\[\/url\]/ism";
1418 $richbody = preg_replace_callback($regexp, ['self', 'mentionCallback'], $item['body']);
1419 $richbody = BBCode::removeAttachment($richbody);
1421 $data['contentMap'][$language] = BBCode::convert($richbody, false);
1424 $data['source'] = ['content' => $item['body'], 'mediaType' => "text/bbcode"];
1426 if (!empty($item['signed_text']) && ($item['uri'] != $item['thr-parent'])) {
1427 $data['diaspora:comment'] = $item['signed_text'];
1430 $data['attachment'] = self::createAttachmentList($item, $type);
1431 $data['tag'] = self::createTagList($item);
1433 if (empty($data['location']) && (!empty($item['coord']) || !empty($item['location']))) {
1434 $data['location'] = self::createLocation($item);
1437 if (!empty($item['app'])) {
1438 $data['generator'] = ['type' => 'Application', 'name' => $item['app']];
1441 $data = array_merge($data, $permission_block);
1447 * Fetches the language from the post, the user or the system.
1449 * @param array $item
1451 * @return string language string
1453 private static function getLanguage(array $item)
1455 // Try to fetch the language from the post itself
1456 if (!empty($item['language'])) {
1457 $languages = array_keys(json_decode($item['language'], true));
1458 if (!empty($languages[0])) {
1459 return $languages[0];
1463 // Otherwise use the user's language
1464 if (!empty($item['uid'])) {
1465 $user = DBA::selectFirst('user', ['language'], ['uid' => $item['uid']]);
1466 if (!empty($user['language'])) {
1467 return $user['language'];
1471 // And finally just use the system language
1472 return DI::config()->get('system', 'language');
1476 * Creates an an "add tag" entry
1478 * @param array $item
1479 * @param array $data activity data
1481 * @return array with activity data for adding tags
1482 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1483 * @throws \ImagickException
1485 private static function createAddTag($item, $data)
1487 $object = XML::parseString($item['object']);
1488 $target = XML::parseString($item["target"]);
1490 $data['diaspora:guid'] = $item['guid'];
1491 $data['actor'] = $item['author-link'];
1492 $data['target'] = (string)$target->id;
1493 $data['summary'] = BBCode::toPlaintext($item['body']);
1494 $data['object'] = ['id' => (string)$object->id, 'type' => 'tag', 'name' => (string)$object->title, 'content' => (string)$object->content];
1500 * Creates an announce object entry
1502 * @param array $item
1503 * @param array $data activity data
1505 * @return array with activity data
1506 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1507 * @throws \ImagickException
1509 private static function createAnnounce($item, $data)
1511 $orig_body = $item['body'];
1512 $announce = self::getAnnounceArray($item);
1513 if (empty($announce)) {
1514 $data['type'] = 'Create';
1515 $data['object'] = self::createNote($item);
1519 if (empty($announce['comment'])) {
1520 // Pure announce, without a quote
1521 $data['type'] = 'Announce';
1522 $data['object'] = $announce['object']['uri'];
1527 $data['type'] = 'Create';
1528 $item['body'] = $announce['comment'] . "\n" . $announce['object']['plink'];
1529 $data['object'] = self::createNote($item);
1531 /// @todo Finally descide how to implement this in AP. This is a possible way:
1532 $data['object']['attachment'][] = self::createNote($announce['object']);
1534 $data['object']['source']['content'] = $orig_body;
1539 * Return announce related data if the item is an annunce
1541 * @param array $item
1545 public static function getAnnounceArray($item)
1547 $reshared = Item::getShareArray($item);
1548 if (empty($reshared['guid'])) {
1552 $reshared_item = Item::selectFirst([], ['guid' => $reshared['guid']]);
1553 if (!DBA::isResult($reshared_item)) {
1557 if (!in_array($reshared_item['network'], [Protocol::ACTIVITYPUB, Protocol::DFRN])) {
1561 $profile = APContact::getByURL($reshared_item['author-link'], false);
1562 if (empty($profile)) {
1566 return ['object' => $reshared_item, 'actor' => $profile, 'comment' => $reshared['comment']];
1570 * Checks if the provided item array is an announce
1572 * @param array $item
1576 public static function isAnnounce($item)
1578 if (!empty($item['verb']) && ($item['verb'] == Activity::ANNOUNCE)) {
1582 $announce = self::getAnnounceArray($item);
1583 if (empty($announce)) {
1587 return empty($announce['comment']);
1591 * Creates an activity id for a given contact id
1593 * @param integer $cid Contact ID of target
1595 * @return bool|string activity id
1597 public static function activityIDFromContact($cid)
1599 $contact = DBA::selectFirst('contact', ['uid', 'id', 'created'], ['id' => $cid]);
1600 if (!DBA::isResult($contact)) {
1604 $hash = hash('ripemd128', $contact['uid'].'-'.$contact['id'].'-'.$contact['created']);
1605 $uuid = substr($hash, 0, 8). '-' . substr($hash, 8, 4) . '-' . substr($hash, 12, 4) . '-' . substr($hash, 16, 4) . '-' . substr($hash, 20, 12);
1606 return DI::baseUrl() . '/activity/' . $uuid;
1610 * Transmits a contact suggestion to a given inbox
1612 * @param integer $uid User ID
1613 * @param string $inbox Target inbox
1614 * @param integer $suggestion_id Suggestion ID
1616 * @return boolean was the transmission successful?
1617 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1619 public static function sendContactSuggestion($uid, $inbox, $suggestion_id)
1621 $owner = User::getOwnerDataById($uid);
1623 $suggestion = DI::fsuggest()->getById($suggestion_id);
1625 $data = ['@context' => ActivityPub::CONTEXT,
1626 'id' => DI::baseUrl() . '/activity/' . System::createGUID(),
1627 'type' => 'Announce',
1628 'actor' => $owner['url'],
1629 'object' => $suggestion->url,
1630 'content' => $suggestion->note,
1631 'instrument' => self::getService(),
1632 'to' => [ActivityPub::PUBLIC_COLLECTION],
1635 $signed = LDSignature::sign($data, $owner);
1637 Logger::log('Deliver profile deletion for user ' . $uid . ' to ' . $inbox . ' via ActivityPub', Logger::DEBUG);
1638 return HTTPSignature::transmit($signed, $inbox, $uid);
1642 * Transmits a profile relocation to a given inbox
1644 * @param integer $uid User ID
1645 * @param string $inbox Target inbox
1647 * @return boolean was the transmission successful?
1648 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1650 public static function sendProfileRelocation($uid, $inbox)
1652 $owner = User::getOwnerDataById($uid);
1654 $data = ['@context' => ActivityPub::CONTEXT,
1655 'id' => DI::baseUrl() . '/activity/' . System::createGUID(),
1656 'type' => 'dfrn:relocate',
1657 'actor' => $owner['url'],
1658 'object' => $owner['url'],
1659 'published' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
1660 'instrument' => self::getService(),
1661 'to' => [ActivityPub::PUBLIC_COLLECTION],
1664 $signed = LDSignature::sign($data, $owner);
1666 Logger::log('Deliver profile relocation for user ' . $uid . ' to ' . $inbox . ' via ActivityPub', Logger::DEBUG);
1667 return HTTPSignature::transmit($signed, $inbox, $uid);
1671 * Transmits a profile deletion to a given inbox
1673 * @param integer $uid User ID
1674 * @param string $inbox Target inbox
1676 * @return boolean was the transmission successful?
1677 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1679 public static function sendProfileDeletion($uid, $inbox)
1681 $owner = User::getOwnerDataById($uid);
1683 if (empty($owner)) {
1684 Logger::error('No owner data found, the deletion message cannot be processed.', ['user' => $uid]);
1688 if (empty($owner['uprvkey'])) {
1689 Logger::error('No private key for owner found, the deletion message cannot be processed.', ['user' => $uid]);
1693 $data = ['@context' => ActivityPub::CONTEXT,
1694 'id' => DI::baseUrl() . '/activity/' . System::createGUID(),
1696 'actor' => $owner['url'],
1697 'object' => $owner['url'],
1698 'published' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
1699 'instrument' => self::getService(),
1700 'to' => [ActivityPub::PUBLIC_COLLECTION],
1703 $signed = LDSignature::sign($data, $owner);
1705 Logger::log('Deliver profile deletion for user ' . $uid . ' to ' . $inbox . ' via ActivityPub', Logger::DEBUG);
1706 return HTTPSignature::transmit($signed, $inbox, $uid);
1710 * Transmits a profile change to a given inbox
1712 * @param integer $uid User ID
1713 * @param string $inbox Target inbox
1715 * @return boolean was the transmission successful?
1716 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1717 * @throws \ImagickException
1719 public static function sendProfileUpdate($uid, $inbox)
1721 $owner = User::getOwnerDataById($uid);
1722 $profile = APContact::getByURL($owner['url']);
1724 $data = ['@context' => ActivityPub::CONTEXT,
1725 'id' => DI::baseUrl() . '/activity/' . System::createGUID(),
1727 'actor' => $owner['url'],
1728 'object' => self::getProfile($uid),
1729 'published' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
1730 'instrument' => self::getService(),
1731 'to' => [$profile['followers']],
1734 $signed = LDSignature::sign($data, $owner);
1736 Logger::log('Deliver profile update for user ' . $uid . ' to ' . $inbox . ' via ActivityPub', Logger::DEBUG);
1737 return HTTPSignature::transmit($signed, $inbox, $uid);
1741 * Transmits a given activity to a target
1743 * @param string $activity Type name
1744 * @param string $target Target profile
1745 * @param integer $uid User ID
1747 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1748 * @throws \ImagickException
1749 * @throws \Exception
1751 public static function sendActivity($activity, $target, $uid, $id = '')
1753 $profile = APContact::getByURL($target);
1754 if (empty($profile['inbox'])) {
1755 Logger::warning('No inbox found for target', ['target' => $target, 'profile' => $profile]);
1759 $owner = User::getOwnerDataById($uid);
1762 $id = DI::baseUrl() . '/activity/' . System::createGUID();
1765 $data = ['@context' => ActivityPub::CONTEXT,
1767 'type' => $activity,
1768 'actor' => $owner['url'],
1769 'object' => $profile['url'],
1770 'instrument' => self::getService(),
1771 'to' => [$profile['url']]];
1773 Logger::log('Sending activity ' . $activity . ' to ' . $target . ' for user ' . $uid, Logger::DEBUG);
1775 $signed = LDSignature::sign($data, $owner);
1776 return HTTPSignature::transmit($signed, $profile['inbox'], $uid);
1780 * Transmits a "follow object" activity to a target
1781 * This is a preparation for sending automated "follow" requests when receiving "Announce" messages
1783 * @param string $object Object URL
1784 * @param string $target Target profile
1785 * @param integer $uid User ID
1787 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1788 * @throws \ImagickException
1789 * @throws \Exception
1791 public static function sendFollowObject($object, $target, $uid = 0)
1793 $profile = APContact::getByURL($target);
1794 if (empty($profile['inbox'])) {
1795 Logger::warning('No inbox found for target', ['target' => $target, 'profile' => $profile]);
1800 // Fetch the list of administrators
1801 $admin_mail = explode(',', str_replace(' ', '', DI::config()->get('config', 'admin_email')));
1803 // We need to use some user as a sender. It doesn't care who it will send. We will use an administrator account.
1804 $condition = ['verified' => true, 'blocked' => false, 'account_removed' => false, 'account_expired' => false, 'email' => $admin_mail];
1805 $first_user = DBA::selectFirst('user', ['uid'], $condition);
1806 $uid = $first_user['uid'];
1809 $condition = ['verb' => Activity::FOLLOW, 'uid' => 0, 'parent-uri' => $object,
1810 'author-id' => Contact::getPublicIdByUserId($uid)];
1811 if (Item::exists($condition)) {
1812 Logger::log('Follow for ' . $object . ' for user ' . $uid . ' does already exist.', Logger::DEBUG);
1816 $owner = User::getOwnerDataById($uid);
1818 $data = ['@context' => ActivityPub::CONTEXT,
1819 'id' => DI::baseUrl() . '/activity/' . System::createGUID(),
1821 'actor' => $owner['url'],
1822 'object' => $object,
1823 'instrument' => self::getService(),
1824 'to' => [$profile['url']]];
1826 Logger::log('Sending follow ' . $object . ' to ' . $target . ' for user ' . $uid, Logger::DEBUG);
1828 $signed = LDSignature::sign($data, $owner);
1829 return HTTPSignature::transmit($signed, $profile['inbox'], $uid);
1833 * Transmit a message that the contact request had been accepted
1835 * @param string $target Target profile
1837 * @param integer $uid User ID
1838 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1839 * @throws \ImagickException
1841 public static function sendContactAccept($target, $id, $uid)
1843 $profile = APContact::getByURL($target);
1844 if (empty($profile['inbox'])) {
1845 Logger::warning('No inbox found for target', ['target' => $target, 'profile' => $profile]);
1849 $owner = User::getOwnerDataById($uid);
1850 $data = ['@context' => ActivityPub::CONTEXT,
1851 'id' => DI::baseUrl() . '/activity/' . System::createGUID(),
1853 'actor' => $owner['url'],
1855 'id' => (string)$id,
1857 'actor' => $profile['url'],
1858 'object' => $owner['url']
1860 'instrument' => self::getService(),
1861 'to' => [$profile['url']]];
1863 Logger::debug('Sending accept to ' . $target . ' for user ' . $uid . ' with id ' . $id);
1865 $signed = LDSignature::sign($data, $owner);
1866 HTTPSignature::transmit($signed, $profile['inbox'], $uid);
1870 * Reject a contact request or terminates the contact relation
1872 * @param string $target Target profile
1874 * @param integer $uid User ID
1875 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1876 * @throws \ImagickException
1878 public static function sendContactReject($target, $id, $uid)
1880 $profile = APContact::getByURL($target);
1881 if (empty($profile['inbox'])) {
1882 Logger::warning('No inbox found for target', ['target' => $target, 'profile' => $profile]);
1886 $owner = User::getOwnerDataById($uid);
1887 $data = ['@context' => ActivityPub::CONTEXT,
1888 'id' => DI::baseUrl() . '/activity/' . System::createGUID(),
1890 'actor' => $owner['url'],
1892 'id' => (string)$id,
1894 'actor' => $profile['url'],
1895 'object' => $owner['url']
1897 'instrument' => self::getService(),
1898 'to' => [$profile['url']]];
1900 Logger::debug('Sending reject to ' . $target . ' for user ' . $uid . ' with id ' . $id);
1902 $signed = LDSignature::sign($data, $owner);
1903 HTTPSignature::transmit($signed, $profile['inbox'], $uid);
1907 * Transmits a message that we don't want to follow this contact anymore
1909 * @param string $target Target profile
1910 * @param integer $uid User ID
1911 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1912 * @throws \ImagickException
1913 * @throws \Exception
1915 public static function sendContactUndo($target, $cid, $uid)
1917 $profile = APContact::getByURL($target);
1918 if (empty($profile['inbox'])) {
1919 Logger::warning('No inbox found for target', ['target' => $target, 'profile' => $profile]);
1923 $object_id = self::activityIDFromContact($cid);
1924 if (empty($object_id)) {
1928 $id = DI::baseUrl() . '/activity/' . System::createGUID();
1930 $owner = User::getOwnerDataById($uid);
1931 $data = ['@context' => ActivityPub::CONTEXT,
1934 'actor' => $owner['url'],
1935 'object' => ['id' => $object_id, 'type' => 'Follow',
1936 'actor' => $owner['url'],
1937 'object' => $profile['url']],
1938 'instrument' => self::getService(),
1939 'to' => [$profile['url']]];
1941 Logger::log('Sending undo to ' . $target . ' for user ' . $uid . ' with id ' . $id, Logger::DEBUG);
1943 $signed = LDSignature::sign($data, $owner);
1944 HTTPSignature::transmit($signed, $profile['inbox'], $uid);
1947 private static function prependMentions($body, int $uriid)
1951 foreach (Tag::getByURIId($uriid, [Tag::IMPLICIT_MENTION]) as $tag) {
1952 $profile = Contact::getByURL($tag['url'], false, ['addr', 'contact-type', 'nick']);
1953 if (!empty($profile['addr'])
1954 && $profile['contact-type'] != Contact::TYPE_COMMUNITY
1955 && !strstr($body, $profile['addr'])
1956 && !strstr($body, $tag['url'])
1958 $mentions[] = '@[url=' . $tag['url'] . ']' . $profile['nick'] . '[/url]';
1962 $mentions[] = $body;
1964 return implode(' ', $mentions);