3 * @copyright Copyright (C) 2020, Friendica
5 * @license GNU AGPL version 3 or any later version
7 * This program is free software: you can redistribute it and/or modify
8 * it under the terms of the GNU Affero General Public License as
9 * published by the Free Software Foundation, either version 3 of the
10 * License, or (at your option) any later version.
12 * This program is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU Affero General Public License for more details.
17 * You should have received a copy of the GNU Affero General Public License
18 * along with this program. If not, see <https://www.gnu.org/licenses/>.
22 namespace Friendica\Protocol\ActivityPub;
24 use Friendica\Content\Feature;
25 use Friendica\Content\Text\BBCode;
26 use Friendica\Content\Text\Plaintext;
27 use Friendica\Core\Cache\Duration;
28 use Friendica\Core\Logger;
29 use Friendica\Core\Protocol;
30 use Friendica\Core\System;
31 use Friendica\Database\DBA;
33 use Friendica\Model\APContact;
34 use Friendica\Model\Contact;
35 use Friendica\Model\Conversation;
36 use Friendica\Model\Item;
37 use Friendica\Model\Profile;
38 use Friendica\Model\Photo;
39 use Friendica\Model\Term;
40 use Friendica\Model\User;
41 use Friendica\Protocol\Activity;
42 use Friendica\Protocol\ActivityPub;
43 use Friendica\Util\DateTimeFormat;
44 use Friendica\Util\HTTPSignature;
45 use Friendica\Util\Images;
46 use Friendica\Util\JsonLD;
47 use Friendica\Util\LDSignature;
48 use Friendica\Util\Map;
49 use Friendica\Util\Network;
50 use Friendica\Util\XML;
52 require_once 'include/api.php';
53 require_once 'mod/share.php';
56 * ActivityPub Transmitter Protocol class
64 * collects the lost of followers of the given owner
66 * @param array $owner Owner array
67 * @param integer $page Page number
69 * @return array of owners
70 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
72 public static function getFollowers($owner, $page = null)
74 $condition = ['rel' => [Contact::FOLLOWER, Contact::FRIEND], 'network' => Protocol::FEDERATED, 'uid' => $owner['uid'],
75 'self' => false, 'deleted' => false, 'hidden' => false, 'archive' => false, 'pending' => false];
76 $count = DBA::count('contact', $condition);
78 $data = ['@context' => ActivityPub::CONTEXT];
79 $data['id'] = DI::baseUrl() . '/followers/' . $owner['nickname'];
80 $data['type'] = 'OrderedCollection';
81 $data['totalItems'] = $count;
83 // When we hide our friends we will only show the pure number but don't allow more.
84 $profile = Profile::getByUID($owner['uid']);
85 if (!empty($profile['hide-friends'])) {
90 $data['first'] = DI::baseUrl() . '/followers/' . $owner['nickname'] . '?page=1';
92 $data['type'] = 'OrderedCollectionPage';
95 $contacts = DBA::select('contact', ['url'], $condition, ['limit' => [($page - 1) * 100, 100]]);
96 while ($contact = DBA::fetch($contacts)) {
97 $list[] = $contact['url'];
101 $data['next'] = DI::baseUrl() . '/followers/' . $owner['nickname'] . '?page=' . ($page + 1);
104 $data['partOf'] = DI::baseUrl() . '/followers/' . $owner['nickname'];
106 $data['orderedItems'] = $list;
113 * Create list of following contacts
115 * @param array $owner Owner array
116 * @param integer $page Page numbe
118 * @return array of following contacts
119 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
121 public static function getFollowing($owner, $page = null)
123 $condition = ['rel' => [Contact::SHARING, Contact::FRIEND], 'network' => Protocol::FEDERATED, 'uid' => $owner['uid'],
124 'self' => false, 'deleted' => false, 'hidden' => false, 'archive' => false, 'pending' => false];
125 $count = DBA::count('contact', $condition);
127 $data = ['@context' => ActivityPub::CONTEXT];
128 $data['id'] = DI::baseUrl() . '/following/' . $owner['nickname'];
129 $data['type'] = 'OrderedCollection';
130 $data['totalItems'] = $count;
132 // When we hide our friends we will only show the pure number but don't allow more.
133 $profile = Profile::getByUID($owner['uid']);
134 if (!empty($profile['hide-friends'])) {
139 $data['first'] = DI::baseUrl() . '/following/' . $owner['nickname'] . '?page=1';
141 $data['type'] = 'OrderedCollectionPage';
144 $contacts = DBA::select('contact', ['url'], $condition, ['limit' => [($page - 1) * 100, 100]]);
145 while ($contact = DBA::fetch($contacts)) {
146 $list[] = $contact['url'];
150 $data['next'] = DI::baseUrl() . '/following/' . $owner['nickname'] . '?page=' . ($page + 1);
153 $data['partOf'] = DI::baseUrl() . '/following/' . $owner['nickname'];
155 $data['orderedItems'] = $list;
162 * Public posts for the given owner
164 * @param array $owner Owner array
165 * @param integer $page Page numbe
167 * @return array of posts
168 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
169 * @throws \ImagickException
171 public static function getOutbox($owner, $page = null)
173 $public_contact = Contact::getIdForURL($owner['url'], 0, true);
175 $condition = ['uid' => 0, 'contact-id' => $public_contact, 'author-id' => $public_contact,
176 'private' => [Item::PUBLIC, Item::UNLISTED], 'gravity' => [GRAVITY_PARENT, GRAVITY_COMMENT],
177 'deleted' => false, 'visible' => true, 'moderated' => false];
178 $count = DBA::count('item', $condition);
180 $data = ['@context' => ActivityPub::CONTEXT];
181 $data['id'] = DI::baseUrl() . '/outbox/' . $owner['nickname'];
182 $data['type'] = 'OrderedCollection';
183 $data['totalItems'] = $count;
186 $data['first'] = DI::baseUrl() . '/outbox/' . $owner['nickname'] . '?page=1';
188 $data['type'] = 'OrderedCollectionPage';
191 $condition['parent-network'] = Protocol::NATIVE_SUPPORT;
193 $items = Item::select(['id'], $condition, ['limit' => [($page - 1) * 20, 20], 'order' => ['created' => true]]);
194 while ($item = Item::fetch($items)) {
195 $activity = self::createActivityFromItem($item['id'], true);
196 // Only list "Create" activity objects here, no reshares
197 if (is_array($activity['object']) && ($activity['type'] == 'Create')) {
198 $list[] = $activity['object'];
203 $data['next'] = DI::baseUrl() . '/outbox/' . $owner['nickname'] . '?page=' . ($page + 1);
206 $data['partOf'] = DI::baseUrl() . '/outbox/' . $owner['nickname'];
208 $data['orderedItems'] = $list;
215 * Return the service array containing information the used software and it's url
217 * @return array with service data
219 private static function getService()
221 return ['type' => 'Service',
222 'name' => FRIENDICA_PLATFORM . " '" . FRIENDICA_CODENAME . "' " . FRIENDICA_VERSION . '-' . DB_UPDATE_VERSION,
223 'url' => DI::baseUrl()->get()];
227 * Return the ActivityPub profile of the given user
229 * @param integer $uid User ID
230 * @return array with profile data
231 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
233 public static function getProfile($uid)
235 $condition = ['uid' => $uid, 'blocked' => false, 'account_expired' => false,
236 'account_removed' => false, 'verified' => true];
237 $fields = ['guid', 'nickname', 'pubkey', 'account-type', 'page-flags'];
238 $user = DBA::selectFirst('user', $fields, $condition);
239 if (!DBA::isResult($user)) {
243 $fields = ['locality', 'region', 'country-name'];
244 $profile = DBA::selectFirst('profile', $fields, ['uid' => $uid]);
245 if (!DBA::isResult($profile)) {
249 $fields = ['name', 'url', 'location', 'about', 'avatar', 'photo'];
250 $contact = DBA::selectFirst('contact', $fields, ['uid' => $uid, 'self' => true]);
251 if (!DBA::isResult($contact)) {
255 $data = ['@context' => ActivityPub::CONTEXT];
256 $data['id'] = $contact['url'];
257 $data['diaspora:guid'] = $user['guid'];
258 $data['type'] = ActivityPub::ACCOUNT_TYPES[$user['account-type']];
259 $data['following'] = DI::baseUrl() . '/following/' . $user['nickname'];
260 $data['followers'] = DI::baseUrl() . '/followers/' . $user['nickname'];
261 $data['inbox'] = DI::baseUrl() . '/inbox/' . $user['nickname'];
262 $data['outbox'] = DI::baseUrl() . '/outbox/' . $user['nickname'];
263 $data['preferredUsername'] = $user['nickname'];
264 $data['name'] = $contact['name'];
265 $data['vcard:hasAddress'] = ['@type' => 'vcard:Home', 'vcard:country-name' => $profile['country-name'],
266 'vcard:region' => $profile['region'], 'vcard:locality' => $profile['locality']];
267 $data['summary'] = BBCode::convert($contact['about'], false);
268 $data['url'] = $contact['url'];
269 $data['manuallyApprovesFollowers'] = in_array($user['page-flags'], [User::PAGE_FLAGS_NORMAL, User::PAGE_FLAGS_PRVGROUP]);
270 $data['publicKey'] = ['id' => $contact['url'] . '#main-key',
271 'owner' => $contact['url'],
272 'publicKeyPem' => $user['pubkey']];
273 $data['endpoints'] = ['sharedInbox' => DI::baseUrl() . '/inbox'];
274 $data['icon'] = ['type' => 'Image',
275 'url' => $contact['photo']];
277 $data['generator'] = self::getService();
279 // tags: https://kitty.town/@inmysocks/100656097926961126.json
284 * @param string $username
286 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
288 public static function getDeletedUser($username)
291 '@context' => ActivityPub::CONTEXT,
292 'id' => DI::baseUrl() . '/profile/' . $username,
293 'type' => 'Tombstone',
294 'published' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
295 'updated' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
296 'deleted' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
301 * Returns an array with permissions of a given item array
305 * @return array with permissions
306 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
307 * @throws \ImagickException
309 private static function fetchPermissionBlockFromConversation($item)
311 if (empty($item['thr-parent'])) {
315 $condition = ['item-uri' => $item['thr-parent'], 'protocol' => Conversation::PARCEL_ACTIVITYPUB];
316 $conversation = DBA::selectFirst('conversation', ['source'], $condition);
317 if (!DBA::isResult($conversation)) {
321 $activity = json_decode($conversation['source'], true);
323 $actor = JsonLD::fetchElement($activity, 'actor', 'id');
324 $profile = APContact::getByURL($actor);
326 $item_profile = APContact::getByURL($item['author-link']);
327 $exclude[] = $item['author-link'];
329 if ($item['gravity'] == GRAVITY_PARENT) {
330 $exclude[] = $item['owner-link'];
333 $permissions['to'][] = $actor;
335 foreach (['to', 'cc', 'bto', 'bcc'] as $element) {
336 if (empty($activity[$element])) {
339 if (is_string($activity[$element])) {
340 $activity[$element] = [$activity[$element]];
343 foreach ($activity[$element] as $receiver) {
344 if (empty($receiver)) {
348 if ($receiver == $profile['followers'] && !empty($item_profile['followers'])) {
349 $permissions[$element][] = $item_profile['followers'];
350 } elseif (!in_array($receiver, $exclude)) {
351 $permissions[$element][] = $receiver;
359 * Creates an array of permissions from an item thread
361 * @param array $item Item array
362 * @param boolean $blindcopy addressing via "bcc" or "cc"?
363 * @param integer $last_id Last item id for adding receivers
364 * @param boolean $forum_mode "true" means that we are sending content to a forum
366 * @return array with permission data
367 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
368 * @throws \ImagickException
370 private static function createPermissionBlockForItem($item, $blindcopy, $last_id = 0, $forum_mode = false)
373 $last_id = $item['id'];
378 // Check if we should always deliver our stuff via BCC
379 if (!empty($item['uid'])) {
380 $profile = Profile::getByUID($item['uid']);
381 if (!empty($profile)) {
382 $always_bcc = $profile['hide-friends'];
386 if (DI::config()->get('system', 'ap_always_bcc')) {
390 if (self::isAnnounce($item) || DI::config()->get('debug', 'total_ap_delivery')) {
391 // Will be activated in a later step
392 $networks = Protocol::FEDERATED;
394 // For now only send to these contacts:
395 $networks = [Protocol::ACTIVITYPUB, Protocol::OSTATUS];
398 $data = ['to' => [], 'cc' => [], 'bcc' => []];
400 if ($item['gravity'] == GRAVITY_PARENT) {
401 $actor_profile = APContact::getByURL($item['owner-link']);
403 $actor_profile = APContact::getByURL($item['author-link']);
406 $terms = Term::tagArrayFromItemId($item['id'], [Term::MENTION, Term::IMPLICIT_MENTION]);
408 if ($item['private'] != Item::PRIVATE) {
409 // Directly mention the original author upon a quoted reshare.
410 // Else just ensure that the original author receives the reshare.
411 $announce = self::getAnnounceArray($item);
412 if (!empty($announce['comment'])) {
413 $data['to'][] = $announce['actor']['url'];
414 } elseif (!empty($announce)) {
415 $data['cc'][] = $announce['actor']['url'];
418 $data = array_merge($data, self::fetchPermissionBlockFromConversation($item));
420 // Check if the item is completely public or unlisted
421 if ($item['private'] == Item::PUBLIC) {
422 $data['to'][] = ActivityPub::PUBLIC_COLLECTION;
424 $data['cc'][] = ActivityPub::PUBLIC_COLLECTION;
427 foreach ($terms as $term) {
428 $profile = APContact::getByURL($term['url'], false);
429 if (!empty($profile)) {
430 $data['to'][] = $profile['url'];
434 $receiver_list = Item::enumeratePermissions($item, true);
436 foreach ($terms as $term) {
437 $cid = Contact::getIdForURL($term['url'], $item['uid']);
438 if (!empty($cid) && in_array($cid, $receiver_list)) {
439 $contact = DBA::selectFirst('contact', ['url', 'network', 'protocol'], ['id' => $cid]);
440 if (!DBA::isResult($contact) || (!in_array($contact['network'], $networks) && ($contact['protocol'] != Protocol::ACTIVITYPUB))) {
444 if (!empty($profile = APContact::getByURL($contact['url'], false))) {
445 $data['to'][] = $profile['url'];
450 foreach ($receiver_list as $receiver) {
451 $contact = DBA::selectFirst('contact', ['url', 'hidden', 'network', 'protocol'], ['id' => $receiver]);
452 if (!DBA::isResult($contact) || (!in_array($contact['network'], $networks) && ($contact['protocol'] != Protocol::ACTIVITYPUB))) {
456 if (!empty($profile = APContact::getByURL($contact['url'], false))) {
457 if ($contact['hidden'] || $always_bcc) {
458 $data['bcc'][] = $profile['url'];
460 $data['cc'][] = $profile['url'];
466 if (!empty($item['parent'])) {
467 $parents = Item::select(['id', 'author-link', 'owner-link', 'gravity', 'uri'], ['parent' => $item['parent']]);
468 while ($parent = Item::fetch($parents)) {
469 if ($parent['gravity'] == GRAVITY_PARENT) {
470 $profile = APContact::getByURL($parent['owner-link'], false);
471 if (!empty($profile)) {
472 if ($item['gravity'] != GRAVITY_PARENT) {
473 // Comments to forums are directed to the forum
474 // But comments to forums aren't directed to the followers collection
475 if ($profile['type'] == 'Group') {
476 $data['to'][] = $profile['url'];
478 $data['cc'][] = $profile['url'];
479 if (($item['private'] != Item::PRIVATE) && $item['private'] && !empty($actor_profile['followers'])) {
480 $data['cc'][] = $actor_profile['followers'];
484 // Public thread parent post always are directed to the followers
485 if (($item['private'] != Item::PRIVATE) && !$forum_mode) {
486 $data['cc'][] = $actor_profile['followers'];
492 // Don't include data from future posts
493 if ($parent['id'] >= $last_id) {
497 $profile = APContact::getByURL($parent['author-link'], false);
498 if (!empty($profile)) {
499 if (($profile['type'] == 'Group') || ($parent['uri'] == $item['thr-parent'])) {
500 $data['to'][] = $profile['url'];
502 $data['cc'][] = $profile['url'];
506 DBA::close($parents);
509 $data['to'] = array_unique($data['to']);
510 $data['cc'] = array_unique($data['cc']);
511 $data['bcc'] = array_unique($data['bcc']);
513 if (($key = array_search($item['author-link'], $data['to'])) !== false) {
514 unset($data['to'][$key]);
517 if (($key = array_search($item['author-link'], $data['cc'])) !== false) {
518 unset($data['cc'][$key]);
521 if (($key = array_search($item['author-link'], $data['bcc'])) !== false) {
522 unset($data['bcc'][$key]);
525 foreach ($data['to'] as $to) {
526 if (($key = array_search($to, $data['cc'])) !== false) {
527 unset($data['cc'][$key]);
530 if (($key = array_search($to, $data['bcc'])) !== false) {
531 unset($data['bcc'][$key]);
535 foreach ($data['cc'] as $cc) {
536 if (($key = array_search($cc, $data['bcc'])) !== false) {
537 unset($data['bcc'][$key]);
541 $receivers = ['to' => array_values($data['to']), 'cc' => array_values($data['cc']), 'bcc' => array_values($data['bcc'])];
544 unset($receivers['bcc']);
551 * Check if an inbox is archived
553 * @param string $url Inbox url
555 * @return boolean "true" if inbox is archived
557 private static function archivedInbox($url)
559 return DBA::exists('inbox-status', ['url' => $url, 'archive' => true]);
563 * Fetches a list of inboxes of followers of a given user
565 * @param integer $uid User ID
566 * @param boolean $personal fetch personal inboxes
568 * @return array of follower inboxes
569 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
570 * @throws \ImagickException
572 public static function fetchTargetInboxesforUser($uid, $personal = false)
576 if (DI::config()->get('debug', 'total_ap_delivery')) {
577 // Will be activated in a later step
578 $networks = Protocol::FEDERATED;
580 // For now only send to these contacts:
581 $networks = [Protocol::ACTIVITYPUB, Protocol::OSTATUS];
584 $condition = ['uid' => $uid, 'archive' => false, 'pending' => false];
587 $condition['rel'] = [Contact::FOLLOWER, Contact::FRIEND];
590 $contacts = DBA::select('contact', ['url', 'network', 'protocol'], $condition);
591 while ($contact = DBA::fetch($contacts)) {
592 if (Contact::isLocal($contact['url'])) {
596 if (!in_array($contact['network'], $networks) && ($contact['protocol'] != Protocol::ACTIVITYPUB)) {
600 if (Network::isUrlBlocked($contact['url'])) {
604 $profile = APContact::getByURL($contact['url'], false);
605 if (!empty($profile)) {
606 if (empty($profile['sharedinbox']) || $personal) {
607 $target = $profile['inbox'];
609 $target = $profile['sharedinbox'];
611 if (!self::archivedInbox($target)) {
612 $inboxes[$target] = $target;
616 DBA::close($contacts);
622 * Fetches an array of inboxes for the given item and user
624 * @param array $item Item array
625 * @param integer $uid User ID
626 * @param boolean $personal fetch personal inboxes
627 * @param integer $last_id Last item id for adding receivers
628 * @param boolean $forum_mode "true" means that we are sending content to a forum
629 * @return array with inboxes
630 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
631 * @throws \ImagickException
633 public static function fetchTargetInboxes($item, $uid, $personal = false, $last_id = 0, $forum_mode = false)
635 $permissions = self::createPermissionBlockForItem($item, true, $last_id, $forum_mode);
636 if (empty($permissions)) {
642 if ($item['gravity'] == GRAVITY_ACTIVITY) {
643 $item_profile = APContact::getByURL($item['author-link'], false);
645 $item_profile = APContact::getByURL($item['owner-link'], false);
648 foreach (['to', 'cc', 'bto', 'bcc'] as $element) {
649 if (empty($permissions[$element])) {
653 $blindcopy = in_array($element, ['bto', 'bcc']);
655 foreach ($permissions[$element] as $receiver) {
656 if (empty($receiver) || Network::isUrlBlocked($receiver)) {
660 if ($receiver == $item_profile['followers']) {
661 $inboxes = array_merge($inboxes, self::fetchTargetInboxesforUser($uid, $personal));
663 if (Contact::isLocal($receiver)) {
667 $profile = APContact::getByURL($receiver, false);
668 if (!empty($profile)) {
669 if (empty($profile['sharedinbox']) || $personal || $blindcopy) {
670 $target = $profile['inbox'];
672 $target = $profile['sharedinbox'];
674 if (!self::archivedInbox($target)) {
675 $inboxes[$target] = $target;
686 * Creates an array in the structure of the item table for a given mail id
688 * @param integer $mail_id
693 public static function ItemArrayFromMail($mail_id)
695 $mail = DBA::selectFirst('mail', [], ['id' => $mail_id]);
696 if (!DBA::isResult($mail)) {
700 $reply = DBA::selectFirst('mail', ['uri'], ['parent-uri' => $mail['parent-uri'], 'reply' => false]);
702 // Making the post more compatible for Mastodon by:
703 // - Making it a note and not an article (no title)
704 // - Moving the title into the "summary" field that is used as a "content warning"
705 $mail['body'] = '[abstract]' . $mail['title'] . "[/abstract]\n" . $mail['body'];
708 $mail['author-link'] = $mail['owner-link'] = $mail['from-url'];
709 $mail['allow_cid'] = '<'.$mail['contact-id'].'>';
710 $mail['allow_gid'] = '';
711 $mail['deny_cid'] = '';
712 $mail['deny_gid'] = '';
713 $mail['private'] = true;
714 $mail['deleted'] = false;
715 $mail['edited'] = $mail['created'];
716 $mail['plink'] = $mail['uri'];
717 $mail['thr-parent'] = $reply['uri'];
718 $mail['gravity'] = ($mail['reply'] ? GRAVITY_COMMENT: GRAVITY_PARENT);
720 $mail['event-type'] = '';
721 $mail['attach'] = '';
729 * Creates an activity array for a given mail id
731 * @param integer $mail_id
732 * @param boolean $object_mode Is the activity item is used inside another object?
734 * @return array of activity
737 public static function createActivityFromMail($mail_id, $object_mode = false)
739 $mail = self::ItemArrayFromMail($mail_id);
740 $object = self::createNote($mail);
743 $data = ['@context' => ActivityPub::CONTEXT];
748 $data['id'] = $mail['uri'] . '#Create';
749 $data['type'] = 'Create';
750 $data['actor'] = $mail['author-link'];
751 $data['published'] = DateTimeFormat::utc($mail['created'] . '+00:00', DateTimeFormat::ATOM);
752 $data['instrument'] = self::getService();
753 $data = array_merge($data, self::createPermissionBlockForItem($mail, true));
755 if (empty($data['to']) && !empty($data['cc'])) {
756 $data['to'] = $data['cc'];
759 if (empty($data['to']) && !empty($data['bcc'])) {
760 $data['to'] = $data['bcc'];
766 $object['to'] = $data['to'];
767 $object['tag'] = [['type' => 'Mention', 'href' => $object['to'][0], 'name' => '']];
769 unset($object['cc']);
770 unset($object['bcc']);
772 $data['directMessage'] = true;
774 $data['object'] = $object;
776 $owner = User::getOwnerDataById($mail['uid']);
778 if (!$object_mode && !empty($owner)) {
779 return LDSignature::sign($data, $owner);
786 * Returns the activity type of a given item
790 * @return string with activity type
791 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
792 * @throws \ImagickException
794 private static function getTypeOfItem($item)
798 // Only check for a reshare, if it is a real reshare and no quoted reshare
799 if (strpos($item['body'], "[share") === 0) {
800 $announce = self::getAnnounceArray($item);
801 $reshared = !empty($announce);
806 } elseif ($item['verb'] == Activity::POST) {
807 if ($item['created'] == $item['edited']) {
812 } elseif ($item['verb'] == Activity::LIKE) {
814 } elseif ($item['verb'] == Activity::DISLIKE) {
816 } elseif ($item['verb'] == Activity::ATTEND) {
818 } elseif ($item['verb'] == Activity::ATTENDNO) {
820 } elseif ($item['verb'] == Activity::ATTENDMAYBE) {
821 $type = 'TentativeAccept';
822 } elseif ($item['verb'] == Activity::FOLLOW) {
824 } elseif ($item['verb'] == Activity::TAG) {
834 * Creates the activity or fetches it from the cache
836 * @param integer $item_id
837 * @param boolean $force Force new cache entry
839 * @return array with the activity
842 public static function createCachedActivityFromItem($item_id, $force = false)
844 $cachekey = 'APDelivery:createActivity:' . $item_id;
847 $data = DI::cache()->get($cachekey);
848 if (!is_null($data)) {
853 $data = ActivityPub\Transmitter::createActivityFromItem($item_id);
855 DI::cache()->set($cachekey, $data, Duration::QUARTER_HOUR);
860 * Creates an activity array for a given item id
862 * @param integer $item_id
863 * @param boolean $object_mode Is the activity item is used inside another object?
865 * @return array of activity
868 public static function createActivityFromItem($item_id, $object_mode = false)
870 $item = Item::selectFirst([], ['id' => $item_id, 'parent-network' => Protocol::NATIVE_SUPPORT]);
872 if (!DBA::isResult($item)) {
876 if ($item['wall'] && ($item['uri'] == $item['parent-uri'])) {
877 $owner = User::getOwnerDataById($item['uid']);
878 if (($owner['account-type'] == User::ACCOUNT_TYPE_COMMUNITY) && ($item['author-link'] != $owner['url'])) {
881 // Disguise forum posts as reshares. Will later be converted to a real announce
882 $item['body'] = share_header($item['author-name'], $item['author-link'], $item['author-avatar'],
883 $item['guid'], $item['created'], $item['plink']) . $item['body'] . '[/share]';
888 $condition = ['item-uri' => $item['uri'], 'protocol' => Conversation::PARCEL_ACTIVITYPUB];
889 $conversation = DBA::selectFirst('conversation', ['source'], $condition);
890 if (DBA::isResult($conversation)) {
891 $data = json_decode($conversation['source'], true);
897 $type = self::getTypeOfItem($item);
901 $data = ['@context' => ActivityPub::CONTEXT];
903 if ($item['deleted'] && ($item['gravity'] == GRAVITY_ACTIVITY)) {
905 } elseif ($item['deleted']) {
912 $data['id'] = $item['uri'] . '#' . $type;
913 $data['type'] = $type;
915 if (Item::isForumPost($item) && ($type != 'Announce')) {
916 $data['actor'] = $item['author-link'];
918 $data['actor'] = $item['owner-link'];
921 $data['published'] = DateTimeFormat::utc($item['created'] . '+00:00', DateTimeFormat::ATOM);
923 $data['instrument'] = self::getService();
925 $data = array_merge($data, self::createPermissionBlockForItem($item, false));
927 if (in_array($data['type'], ['Create', 'Update', 'Delete'])) {
928 $data['object'] = self::createNote($item);
929 } elseif ($data['type'] == 'Add') {
930 $data = self::createAddTag($item, $data);
931 } elseif ($data['type'] == 'Announce') {
932 $data = self::createAnnounce($item, $data);
933 } elseif ($data['type'] == 'Follow') {
934 $data['object'] = $item['parent-uri'];
935 } elseif ($data['type'] == 'Undo') {
936 $data['object'] = self::createActivityFromItem($item_id, true);
938 $data['diaspora:guid'] = $item['guid'];
939 if (!empty($item['signed_text'])) {
940 $data['diaspora:like'] = $item['signed_text'];
942 $data['object'] = $item['thr-parent'];
945 if (!empty($item['contact-uid'])) {
946 $uid = $item['contact-uid'];
951 $owner = User::getOwnerDataById($uid);
953 if (!$object_mode && !empty($owner)) {
954 return LDSignature::sign($data, $owner);
959 /// @todo Create "conversation" entry
963 * Creates a location entry for a given item array
967 * @return array with location array
969 private static function createLocation($item)
971 $location = ['type' => 'Place'];
973 if (!empty($item['location'])) {
974 $location['name'] = $item['location'];
979 if (empty($item['coord'])) {
980 $coord = Map::getCoordinates($item['location']);
982 $coords = explode(' ', $item['coord']);
983 if (count($coords) == 2) {
984 $coord = ['lat' => $coords[0], 'lon' => $coords[1]];
988 if (!empty($coord['lat']) && !empty($coord['lon'])) {
989 $location['latitude'] = $coord['lat'];
990 $location['longitude'] = $coord['lon'];
997 * Returns a tag array for a given item array
1001 * @return array of tags
1002 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1004 private static function createTagList($item)
1008 $terms = Term::tagArrayFromItemId($item['id'], [Term::HASHTAG, Term::MENTION, Term::IMPLICIT_MENTION]);
1009 foreach ($terms as $term) {
1010 if ($term['type'] == Term::HASHTAG) {
1011 $url = DI::baseUrl() . '/search?tag=' . urlencode($term['term']);
1012 $tags[] = ['type' => 'Hashtag', 'href' => $url, 'name' => '#' . $term['term']];
1013 } elseif ($term['type'] == Term::MENTION || $term['type'] == Term::IMPLICIT_MENTION) {
1014 $contact = Contact::getDetailsByURL($term['url']);
1015 if (!empty($contact['addr'])) {
1016 $mention = '@' . $contact['addr'];
1018 $mention = '@' . $term['url'];
1021 $tags[] = ['type' => 'Mention', 'href' => $term['url'], 'name' => $mention];
1025 $announce = self::getAnnounceArray($item);
1026 // Mention the original author upon commented reshares
1027 if (!empty($announce['comment'])) {
1028 $tags[] = ['type' => 'Mention', 'href' => $announce['actor']['url'], 'name' => '@' . $announce['actor']['addr']];
1035 * Adds attachment data to the JSON document
1037 * @param array $item Data of the item that is to be posted
1038 * @param string $type Object type
1040 * @return array with attachment data
1041 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1043 private static function createAttachmentList($item, $type)
1047 // Currently deactivated, since it creates side effects on Mastodon and Pleroma.
1048 // It will be reactivated, once this cleared.
1050 $attach_data = BBCode::getAttachmentData($item['body']);
1051 if (!empty($attach_data['url'])) {
1052 $attachment = ['type' => 'Page',
1053 'mediaType' => 'text/html',
1054 'url' => $attach_data['url']];
1056 if (!empty($attach_data['title'])) {
1057 $attachment['name'] = $attach_data['title'];
1060 if (!empty($attach_data['description'])) {
1061 $attachment['summary'] = $attach_data['description'];
1064 if (!empty($attach_data['image'])) {
1065 $imgdata = Images::getInfoFromURLCached($attach_data['image']);
1067 $attachment['icon'] = ['type' => 'Image',
1068 'mediaType' => $imgdata['mime'],
1069 'width' => $imgdata[0],
1070 'height' => $imgdata[1],
1071 'url' => $attach_data['image']];
1075 $attachments[] = $attachment;
1078 $arr = explode('[/attach],', $item['attach']);
1080 foreach ($arr as $r) {
1082 $cnt = preg_match('|\[attach\]href=\"(.*?)\" length=\"(.*?)\" type=\"(.*?)\" title=\"(.*?)\"|', $r, $matches);
1084 $attributes = ['type' => 'Document',
1085 'mediaType' => $matches[3],
1086 'url' => $matches[1],
1089 if (trim($matches[4]) != '') {
1090 $attributes['name'] = trim($matches[4]);
1093 $attachments[] = $attributes;
1098 if ($type != 'Note') {
1099 return $attachments;
1102 // Simplify image codes
1103 $body = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '[img]$3[/img]', $item['body']);
1105 // Grab all pictures without alternative descriptions and create attachments out of them
1106 if (preg_match_all("/\[img\]([^\[\]]*)\[\/img\]/Usi", $body, $pictures)) {
1107 foreach ($pictures[1] as $picture) {
1108 $imgdata = Images::getInfoFromURLCached($picture);
1110 $attachments[] = ['type' => 'Document',
1111 'mediaType' => $imgdata['mime'],
1118 // Grab all pictures with alternative description and create attachments out of them
1119 if (preg_match_all("/\[img=([^\[\]]*)\]([^\[\]]*)\[\/img\]/Usi", $body, $pictures, PREG_SET_ORDER)) {
1120 foreach ($pictures as $picture) {
1121 $imgdata = Images::getInfoFromURLCached($picture[1]);
1123 $attachments[] = ['type' => 'Document',
1124 'mediaType' => $imgdata['mime'],
1125 'url' => $picture[1],
1126 'name' => $picture[2]];
1131 return $attachments;
1135 * Callback function to replace a Friendica style mention in a mention that is used on AP
1137 * @param array $match Matching values for the callback
1138 * @return string Replaced mention
1139 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1141 private static function mentionCallback($match)
1143 if (empty($match[1])) {
1147 $data = Contact::getDetailsByURL($match[1]);
1148 if (empty($data['nick'])) {
1152 return '@[url=' . $data['url'] . ']' . $data['nick'] . '[/url]';
1156 * Remove image elements since they are added as attachment
1158 * @param string $body
1160 * @return string with removed images
1162 private static function removePictures($body)
1164 // Simplify image codes
1165 $body = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '[img]$3[/img]', $body);
1166 $body = preg_replace("/\[img\=(.*?)\](.*?)\[\/img\]/ism", '[img]$1[/img]', $body);
1168 // Now remove local links
1169 $body = preg_replace_callback(
1170 '/\[url=([^\[\]]*)\]\[img\](.*)\[\/img\]\[\/url\]/Usi',
1172 // We remove the link when it is a link to a local photo page
1173 if (Photo::isLocalPage($match[1])) {
1176 // otherwise we just return the link
1177 return '[url]' . $match[1] . '[/url]';
1182 // Remove all pictures
1183 $body = preg_replace("/\[img\]([^\[\]]*)\[\/img\]/Usi", '', $body);
1189 * Fetches the "context" value for a givem item array from the "conversation" table
1191 * @param array $item
1193 * @return string with context url
1194 * @throws \Exception
1196 private static function fetchContextURLForItem($item)
1198 $conversation = DBA::selectFirst('conversation', ['conversation-href', 'conversation-uri'], ['item-uri' => $item['parent-uri']]);
1199 if (DBA::isResult($conversation) && !empty($conversation['conversation-href'])) {
1200 $context_uri = $conversation['conversation-href'];
1201 } elseif (DBA::isResult($conversation) && !empty($conversation['conversation-uri'])) {
1202 $context_uri = $conversation['conversation-uri'];
1204 $context_uri = $item['parent-uri'] . '#context';
1206 return $context_uri;
1210 * Returns if the post contains sensitive content ("nsfw")
1212 * @param integer $item_id
1215 * @throws \Exception
1217 private static function isSensitive($item_id)
1219 $condition = ['otype' => TERM_OBJ_POST, 'oid' => $item_id, 'type' => TERM_HASHTAG, 'term' => 'nsfw'];
1220 return DBA::exists('term', $condition);
1224 * Creates event data
1226 * @param array $item
1228 * @return array with the event data
1229 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1231 public static function createEvent($item)
1234 $event['name'] = $item['event-summary'];
1235 $event['content'] = BBCode::convert($item['event-desc'], false, 9);
1236 $event['startTime'] = DateTimeFormat::utc($item['event-start'] . '+00:00', DateTimeFormat::ATOM);
1238 if (!$item['event-nofinish']) {
1239 $event['endTime'] = DateTimeFormat::utc($item['event-finish'] . '+00:00', DateTimeFormat::ATOM);
1242 if (!empty($item['event-location'])) {
1243 $item['location'] = $item['event-location'];
1244 $event['location'] = self::createLocation($item);
1251 * Creates a note/article object array
1253 * @param array $item
1255 * @return array with the object data
1256 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1257 * @throws \ImagickException
1259 public static function createNote($item)
1265 if ($item['event-type'] == 'event') {
1267 } elseif (!empty($item['title'])) {
1273 if ($item['deleted']) {
1274 $type = 'Tombstone';
1278 $data['id'] = $item['uri'];
1279 $data['type'] = $type;
1281 if ($item['deleted']) {
1285 $data['summary'] = BBCode::toPlaintext(BBCode::getAbstract($item['body'], Protocol::ACTIVITYPUB));
1287 if ($item['uri'] != $item['thr-parent']) {
1288 $data['inReplyTo'] = $item['thr-parent'];
1290 $data['inReplyTo'] = null;
1293 $data['diaspora:guid'] = $item['guid'];
1294 $data['published'] = DateTimeFormat::utc($item['created'] . '+00:00', DateTimeFormat::ATOM);
1296 if ($item['created'] != $item['edited']) {
1297 $data['updated'] = DateTimeFormat::utc($item['edited'] . '+00:00', DateTimeFormat::ATOM);
1300 $data['url'] = $item['plink'];
1301 $data['attributedTo'] = $item['author-link'];
1302 $data['sensitive'] = self::isSensitive($item['id']);
1303 $data['context'] = self::fetchContextURLForItem($item);
1305 if (!empty($item['title'])) {
1306 $data['name'] = BBCode::toPlaintext($item['title'], false);
1309 $permission_block = self::createPermissionBlockForItem($item, false);
1311 $body = $item['body'];
1313 if (empty($item['uid']) || !Feature::isEnabled($item['uid'], 'explicit_mentions')) {
1314 $body = self::prependMentions($body, $permission_block);
1317 if ($type == 'Note') {
1318 $body = self::removePictures($body);
1319 } elseif (($type == 'Article') && empty($data['summary'])) {
1320 $data['summary'] = BBCode::toPlaintext(Plaintext::shorten(self::removePictures($body), 1000));
1323 if ($type == 'Event') {
1324 $data = array_merge($data, self::createEvent($item));
1326 $regexp = "/[@!]\[url\=([^\[\]]*)\].*?\[\/url\]/ism";
1327 $body = preg_replace_callback($regexp, ['self', 'mentionCallback'], $body);
1329 $data['content'] = BBCode::convert($body, false, 9);
1332 // The regular "content" field does contain a minimized HTML. This is done since systems like
1333 // Mastodon has got problems with - for example - embedded pictures.
1334 // The contentMap does contain the unmodified HTML.
1335 $language = self::getLanguage($item);
1336 if (!empty($language)) {
1337 $regexp = "/[@!]\[url\=([^\[\]]*)\].*?\[\/url\]/ism";
1338 $richbody = preg_replace_callback($regexp, ['self', 'mentionCallback'], $item['body']);
1339 $richbody = BBCode::removeAttachment($richbody);
1341 $data['contentMap'][$language] = BBCode::convert($richbody, false);
1344 $data['source'] = ['content' => $item['body'], 'mediaType' => "text/bbcode"];
1346 if (!empty($item['signed_text']) && ($item['uri'] != $item['thr-parent'])) {
1347 $data['diaspora:comment'] = $item['signed_text'];
1350 $data['attachment'] = self::createAttachmentList($item, $type);
1351 $data['tag'] = self::createTagList($item);
1353 if (empty($data['location']) && (!empty($item['coord']) || !empty($item['location']))) {
1354 $data['location'] = self::createLocation($item);
1357 if (!empty($item['app'])) {
1358 $data['generator'] = ['type' => 'Application', 'name' => $item['app']];
1361 $data = array_merge($data, $permission_block);
1367 * Fetches the language from the post, the user or the system.
1369 * @param array $item
1371 * @return string language string
1373 private static function getLanguage(array $item)
1375 // Try to fetch the language from the post itself
1376 if (!empty($item['language'])) {
1377 $languages = array_keys(json_decode($item['language'], true));
1378 if (!empty($languages[0])) {
1379 return $languages[0];
1383 // Otherwise use the user's language
1384 if (!empty($item['uid'])) {
1385 $user = DBA::selectFirst('user', ['language'], ['uid' => $item['uid']]);
1386 if (!empty($user['language'])) {
1387 return $user['language'];
1391 // And finally just use the system language
1392 return DI::config()->get('system', 'language');
1396 * Creates an an "add tag" entry
1398 * @param array $item
1399 * @param array $data activity data
1401 * @return array with activity data for adding tags
1402 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1403 * @throws \ImagickException
1405 private static function createAddTag($item, $data)
1407 $object = XML::parseString($item['object'], false);
1408 $target = XML::parseString($item["target"], false);
1410 $data['diaspora:guid'] = $item['guid'];
1411 $data['actor'] = $item['author-link'];
1412 $data['target'] = (string)$target->id;
1413 $data['summary'] = BBCode::toPlaintext($item['body']);
1414 $data['object'] = ['id' => (string)$object->id, 'type' => 'tag', 'name' => (string)$object->title, 'content' => (string)$object->content];
1420 * Creates an announce object entry
1422 * @param array $item
1423 * @param array $data activity data
1425 * @return array with activity data
1426 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1427 * @throws \ImagickException
1429 private static function createAnnounce($item, $data)
1431 $orig_body = $item['body'];
1432 $announce = self::getAnnounceArray($item);
1433 if (empty($announce)) {
1434 $data['type'] = 'Create';
1435 $data['object'] = self::createNote($item);
1439 if (empty($announce['comment'])) {
1440 // Pure announce, without a quote
1441 $data['type'] = 'Announce';
1442 $data['object'] = $announce['object']['uri'];
1447 $data['type'] = 'Create';
1448 $item['body'] = $announce['comment'] . "\n" . $announce['object']['plink'];
1449 $data['object'] = self::createNote($item);
1451 /// @todo Finally descide how to implement this in AP. This is a possible way:
1452 $data['object']['attachment'][] = self::createNote($announce['object']);
1454 $data['object']['source']['content'] = $orig_body;
1459 * Return announce related data if the item is an annunce
1461 * @param array $item
1465 public static function getAnnounceArray($item)
1467 $reshared = Item::getShareArray($item);
1468 if (empty($reshared['guid'])) {
1472 $reshared_item = Item::selectFirst([], ['guid' => $reshared['guid']]);
1473 if (!DBA::isResult($reshared_item)) {
1477 if (!in_array($reshared_item['network'], [Protocol::ACTIVITYPUB, Protocol::DFRN])) {
1481 $profile = APContact::getByURL($reshared_item['author-link'], false);
1482 if (empty($profile)) {
1486 return ['object' => $reshared_item, 'actor' => $profile, 'comment' => $reshared['comment']];
1490 * Checks if the provided item array is an announce
1492 * @param array $item
1496 public static function isAnnounce($item)
1498 $announce = self::getAnnounceArray($item);
1499 if (empty($announce)) {
1503 return empty($announce['comment']);
1507 * Creates an activity id for a given contact id
1509 * @param integer $cid Contact ID of target
1511 * @return bool|string activity id
1513 public static function activityIDFromContact($cid)
1515 $contact = DBA::selectFirst('contact', ['uid', 'id', 'created'], ['id' => $cid]);
1516 if (!DBA::isResult($contact)) {
1520 $hash = hash('ripemd128', $contact['uid'].'-'.$contact['id'].'-'.$contact['created']);
1521 $uuid = substr($hash, 0, 8). '-' . substr($hash, 8, 4) . '-' . substr($hash, 12, 4) . '-' . substr($hash, 16, 4) . '-' . substr($hash, 20, 12);
1522 return DI::baseUrl() . '/activity/' . $uuid;
1526 * Transmits a contact suggestion to a given inbox
1528 * @param integer $uid User ID
1529 * @param string $inbox Target inbox
1530 * @param integer $suggestion_id Suggestion ID
1532 * @return boolean was the transmission successful?
1533 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1535 public static function sendContactSuggestion($uid, $inbox, $suggestion_id)
1537 $owner = User::getOwnerDataById($uid);
1539 $suggestion = DI::fsuggest()->getById($suggestion_id);
1541 $data = ['@context' => ActivityPub::CONTEXT,
1542 'id' => DI::baseUrl() . '/activity/' . System::createGUID(),
1543 'type' => 'Announce',
1544 'actor' => $owner['url'],
1545 'object' => $suggestion->url,
1546 'content' => $suggestion->note,
1547 'instrument' => self::getService(),
1548 'to' => [ActivityPub::PUBLIC_COLLECTION],
1551 $signed = LDSignature::sign($data, $owner);
1553 Logger::log('Deliver profile deletion for user ' . $uid . ' to ' . $inbox . ' via ActivityPub', Logger::DEBUG);
1554 return HTTPSignature::transmit($signed, $inbox, $uid);
1558 * Transmits a profile relocation to a given inbox
1560 * @param integer $uid User ID
1561 * @param string $inbox Target inbox
1563 * @return boolean was the transmission successful?
1564 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1566 public static function sendProfileRelocation($uid, $inbox)
1568 $owner = User::getOwnerDataById($uid);
1570 $data = ['@context' => ActivityPub::CONTEXT,
1571 'id' => DI::baseUrl() . '/activity/' . System::createGUID(),
1572 'type' => 'dfrn:relocate',
1573 'actor' => $owner['url'],
1574 'object' => $owner['url'],
1575 'published' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
1576 'instrument' => self::getService(),
1577 'to' => [ActivityPub::PUBLIC_COLLECTION],
1580 $signed = LDSignature::sign($data, $owner);
1582 Logger::log('Deliver profile relocation for user ' . $uid . ' to ' . $inbox . ' via ActivityPub', Logger::DEBUG);
1583 return HTTPSignature::transmit($signed, $inbox, $uid);
1587 * Transmits a profile deletion to a given inbox
1589 * @param integer $uid User ID
1590 * @param string $inbox Target inbox
1592 * @return boolean was the transmission successful?
1593 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1595 public static function sendProfileDeletion($uid, $inbox)
1597 $owner = User::getOwnerDataById($uid);
1599 if (empty($owner)) {
1600 Logger::error('No owner data found, the deletion message cannot be processed.', ['user' => $uid]);
1604 if (empty($owner['uprvkey'])) {
1605 Logger::error('No private key for owner found, the deletion message cannot be processed.', ['user' => $uid]);
1609 $data = ['@context' => ActivityPub::CONTEXT,
1610 'id' => DI::baseUrl() . '/activity/' . System::createGUID(),
1612 'actor' => $owner['url'],
1613 'object' => $owner['url'],
1614 'published' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
1615 'instrument' => self::getService(),
1616 'to' => [ActivityPub::PUBLIC_COLLECTION],
1619 $signed = LDSignature::sign($data, $owner);
1621 Logger::log('Deliver profile deletion for user ' . $uid . ' to ' . $inbox . ' via ActivityPub', Logger::DEBUG);
1622 return HTTPSignature::transmit($signed, $inbox, $uid);
1626 * Transmits a profile change to a given inbox
1628 * @param integer $uid User ID
1629 * @param string $inbox Target inbox
1631 * @return boolean was the transmission successful?
1632 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1633 * @throws \ImagickException
1635 public static function sendProfileUpdate($uid, $inbox)
1637 $owner = User::getOwnerDataById($uid);
1638 $profile = APContact::getByURL($owner['url']);
1640 $data = ['@context' => ActivityPub::CONTEXT,
1641 'id' => DI::baseUrl() . '/activity/' . System::createGUID(),
1643 'actor' => $owner['url'],
1644 'object' => self::getProfile($uid),
1645 'published' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
1646 'instrument' => self::getService(),
1647 'to' => [$profile['followers']],
1650 $signed = LDSignature::sign($data, $owner);
1652 Logger::log('Deliver profile update for user ' . $uid . ' to ' . $inbox . ' via ActivityPub', Logger::DEBUG);
1653 return HTTPSignature::transmit($signed, $inbox, $uid);
1657 * Transmits a given activity to a target
1659 * @param string $activity Type name
1660 * @param string $target Target profile
1661 * @param integer $uid User ID
1663 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1664 * @throws \ImagickException
1665 * @throws \Exception
1667 public static function sendActivity($activity, $target, $uid, $id = '')
1669 $profile = APContact::getByURL($target);
1670 if (empty($profile['inbox'])) {
1671 Logger::warning('No inbox found for target', ['target' => $target, 'profile' => $profile]);
1675 $owner = User::getOwnerDataById($uid);
1678 $id = DI::baseUrl() . '/activity/' . System::createGUID();
1681 $data = ['@context' => ActivityPub::CONTEXT,
1683 'type' => $activity,
1684 'actor' => $owner['url'],
1685 'object' => $profile['url'],
1686 'instrument' => self::getService(),
1687 'to' => [$profile['url']]];
1689 Logger::log('Sending activity ' . $activity . ' to ' . $target . ' for user ' . $uid, Logger::DEBUG);
1691 $signed = LDSignature::sign($data, $owner);
1692 return HTTPSignature::transmit($signed, $profile['inbox'], $uid);
1696 * Transmits a "follow object" activity to a target
1697 * This is a preparation for sending automated "follow" requests when receiving "Announce" messages
1699 * @param string $object Object URL
1700 * @param string $target Target profile
1701 * @param integer $uid User ID
1703 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1704 * @throws \ImagickException
1705 * @throws \Exception
1707 public static function sendFollowObject($object, $target, $uid = 0)
1709 $profile = APContact::getByURL($target);
1710 if (empty($profile['inbox'])) {
1711 Logger::warning('No inbox found for target', ['target' => $target, 'profile' => $profile]);
1716 // Fetch the list of administrators
1717 $admin_mail = explode(',', str_replace(' ', '', DI::config()->get('config', 'admin_email')));
1719 // We need to use some user as a sender. It doesn't care who it will send. We will use an administrator account.
1720 $condition = ['verified' => true, 'blocked' => false, 'account_removed' => false, 'account_expired' => false, 'email' => $admin_mail];
1721 $first_user = DBA::selectFirst('user', ['uid'], $condition);
1722 $uid = $first_user['uid'];
1725 $condition = ['verb' => Activity::FOLLOW, 'uid' => 0, 'parent-uri' => $object,
1726 'author-id' => Contact::getPublicIdByUserId($uid)];
1727 if (Item::exists($condition)) {
1728 Logger::log('Follow for ' . $object . ' for user ' . $uid . ' does already exist.', Logger::DEBUG);
1732 $owner = User::getOwnerDataById($uid);
1734 $data = ['@context' => ActivityPub::CONTEXT,
1735 'id' => DI::baseUrl() . '/activity/' . System::createGUID(),
1737 'actor' => $owner['url'],
1738 'object' => $object,
1739 'instrument' => self::getService(),
1740 'to' => [$profile['url']]];
1742 Logger::log('Sending follow ' . $object . ' to ' . $target . ' for user ' . $uid, Logger::DEBUG);
1744 $signed = LDSignature::sign($data, $owner);
1745 return HTTPSignature::transmit($signed, $profile['inbox'], $uid);
1749 * Transmit a message that the contact request had been accepted
1751 * @param string $target Target profile
1753 * @param integer $uid User ID
1754 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1755 * @throws \ImagickException
1757 public static function sendContactAccept($target, $id, $uid)
1759 $profile = APContact::getByURL($target);
1760 if (empty($profile['inbox'])) {
1761 Logger::warning('No inbox found for target', ['target' => $target, 'profile' => $profile]);
1765 $owner = User::getOwnerDataById($uid);
1766 $data = ['@context' => ActivityPub::CONTEXT,
1767 'id' => DI::baseUrl() . '/activity/' . System::createGUID(),
1769 'actor' => $owner['url'],
1771 'id' => (string)$id,
1773 'actor' => $profile['url'],
1774 'object' => $owner['url']
1776 'instrument' => self::getService(),
1777 'to' => [$profile['url']]];
1779 Logger::debug('Sending accept to ' . $target . ' for user ' . $uid . ' with id ' . $id);
1781 $signed = LDSignature::sign($data, $owner);
1782 HTTPSignature::transmit($signed, $profile['inbox'], $uid);
1786 * Reject a contact request or terminates the contact relation
1788 * @param string $target Target profile
1790 * @param integer $uid User ID
1791 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1792 * @throws \ImagickException
1794 public static function sendContactReject($target, $id, $uid)
1796 $profile = APContact::getByURL($target);
1797 if (empty($profile['inbox'])) {
1798 Logger::warning('No inbox found for target', ['target' => $target, 'profile' => $profile]);
1802 $owner = User::getOwnerDataById($uid);
1803 $data = ['@context' => ActivityPub::CONTEXT,
1804 'id' => DI::baseUrl() . '/activity/' . System::createGUID(),
1806 'actor' => $owner['url'],
1808 'id' => (string)$id,
1810 'actor' => $profile['url'],
1811 'object' => $owner['url']
1813 'instrument' => self::getService(),
1814 'to' => [$profile['url']]];
1816 Logger::debug('Sending reject to ' . $target . ' for user ' . $uid . ' with id ' . $id);
1818 $signed = LDSignature::sign($data, $owner);
1819 HTTPSignature::transmit($signed, $profile['inbox'], $uid);
1823 * Transmits a message that we don't want to follow this contact anymore
1825 * @param string $target Target profile
1826 * @param integer $uid User ID
1827 * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1828 * @throws \ImagickException
1829 * @throws \Exception
1831 public static function sendContactUndo($target, $cid, $uid)
1833 $profile = APContact::getByURL($target);
1834 if (empty($profile['inbox'])) {
1835 Logger::warning('No inbox found for target', ['target' => $target, 'profile' => $profile]);
1839 $object_id = self::activityIDFromContact($cid);
1840 if (empty($object_id)) {
1844 $id = DI::baseUrl() . '/activity/' . System::createGUID();
1846 $owner = User::getOwnerDataById($uid);
1847 $data = ['@context' => ActivityPub::CONTEXT,
1850 'actor' => $owner['url'],
1851 'object' => ['id' => $object_id, 'type' => 'Follow',
1852 'actor' => $owner['url'],
1853 'object' => $profile['url']],
1854 'instrument' => self::getService(),
1855 'to' => [$profile['url']]];
1857 Logger::log('Sending undo to ' . $target . ' for user ' . $uid . ' with id ' . $id, Logger::DEBUG);
1859 $signed = LDSignature::sign($data, $owner);
1860 HTTPSignature::transmit($signed, $profile['inbox'], $uid);
1863 private static function prependMentions($body, array $permission_block)
1865 if (DI::config()->get('system', 'disable_implicit_mentions')) {
1871 foreach ($permission_block['to'] as $profile_url) {
1872 $profile = Contact::getDetailsByURL($profile_url);
1873 if (!empty($profile['addr'])
1874 && $profile['contact-type'] != Contact::TYPE_COMMUNITY
1875 && !strstr($body, $profile['addr'])
1876 && !strstr($body, $profile_url)
1878 $mentions[] = '@[url=' . $profile_url . ']' . $profile['nick'] . '[/url]';
1882 $mentions[] = $body;
1884 return implode(' ', $mentions);