]> git.mxchange.org Git - friendica.git/blob - src/Protocol/ActivityPub/Transmitter.php
6a1dacf0a36c9cacb2145010cdc8fcc3c16ea01a
[friendica.git] / src / Protocol / ActivityPub / Transmitter.php
1 <?php
2 /**
3  * @copyright Copyright (C) 2010-2022, the Friendica project
4  *
5  * @license GNU AGPL version 3 or any later version
6  *
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.
11  *
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.
16  *
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/>.
19  *
20  */
21
22 namespace Friendica\Protocol\ActivityPub;
23
24 use Friendica\Content\Feature;
25 use Friendica\Content\Text\BBCode;
26 use Friendica\Core\Cache\Enum\Duration;
27 use Friendica\Core\Logger;
28 use Friendica\Core\Protocol;
29 use Friendica\Core\System;
30 use Friendica\Database\DBA;
31 use Friendica\DI;
32 use Friendica\Model\APContact;
33 use Friendica\Model\Contact;
34 use Friendica\Model\Conversation;
35 use Friendica\Model\GServer;
36 use Friendica\Model\Item;
37 use Friendica\Model\Photo;
38 use Friendica\Model\Post;
39 use Friendica\Model\Tag;
40 use Friendica\Model\User;
41 use Friendica\Network\HTTPException;
42 use Friendica\Protocol\Activity;
43 use Friendica\Protocol\ActivityPub;
44 use Friendica\Protocol\Relay;
45 use Friendica\Util\DateTimeFormat;
46 use Friendica\Util\HTTPSignature;
47 use Friendica\Util\JsonLD;
48 use Friendica\Util\LDSignature;
49 use Friendica\Util\Map;
50 use Friendica\Util\Network;
51 use Friendica\Util\Strings;
52 use Friendica\Util\XML;
53
54 /**
55  * ActivityPub Transmitter Protocol class
56  *
57  * To-Do:
58  * @todo Undo Announce
59  */
60 class Transmitter
61 {
62         /**
63          * Add relay servers to the list of inboxes
64          *
65          * @param array $inboxes
66          * @return array inboxes with added relay servers
67          */
68         public static function addRelayServerInboxes(array $inboxes = [])
69         {
70                 foreach (Relay::getList(['inbox']) as $contact) {
71                         $inboxes[$contact['inbox']] = $contact['inbox'];
72                 }
73
74                 return $inboxes;
75         }
76
77         /**
78          * Add relay servers to the list of inboxes
79          *
80          * @param array $inboxes
81          * @return array inboxes with added relay servers
82          */
83         public static function addRelayServerInboxesForItem(int $item_id, array $inboxes = [])
84         {
85                 $item = Post::selectFirst(['uid'], ['id' => $item_id]);
86                 if (empty($item)) {
87                         return $inboxes;
88                 }
89
90                 $relays = Relay::getDirectRelayList($item_id);
91                 if (empty($relays)) {
92                         return $inboxes;
93                 }
94
95                 foreach ($relays as $relay) {
96                         $contact = Contact::getByURLForUser($relay['url'], $item['uid'], false, ['id']);
97                         $inboxes[$relay['batch']][] = $contact['id'] ?? 0;
98                 }
99                 return $inboxes;
100         }
101
102         /**
103          * Subscribe to a relay
104          *
105          * @param string $url Subscribe actor url
106          * @return bool success
107          */
108         public static function sendRelayFollow(string $url)
109         {
110                 $contact = Contact::getByURL($url);
111                 if (empty($contact)) {
112                         return false;
113                 }
114
115                 $activity_id = ActivityPub\Transmitter::activityIDFromContact($contact['id']);
116                 $success = ActivityPub\Transmitter::sendActivity('Follow', $url, 0, $activity_id);
117                 if ($success) {
118                         Contact::update(['rel' => Contact::FRIEND], ['id' => $contact['id']]);
119                 }
120
121                 return $success;
122         }
123
124         /**
125          * Unsubscribe from a relay
126          *
127          * @param string $url   Subscribe actor url
128          * @param bool   $force Set the relay status as non follower even if unsubscribe hadn't worked
129          * @return bool success
130          */
131         public static function sendRelayUndoFollow(string $url, bool $force = false)
132         {
133                 $contact = Contact::getByURL($url);
134                 if (empty($contact)) {
135                         return false;
136                 }
137
138                 $success = self::sendContactUndo($url, $contact['id'], 0);
139                 if ($success || $force) {
140                         Contact::update(['rel' => Contact::NOTHING], ['id' => $contact['id']]);
141                 }
142
143                 return $success;
144         }
145
146         /**
147          * Collects a list of contacts of the given owner
148          *
149          * @param array     $owner     Owner array
150          * @param int|array $rel       The relevant value(s) contact.rel should match
151          * @param string    $module    The name of the relevant AP endpoint module (followers|following)
152          * @param integer   $page      Page number
153          * @param string    $requester URL of the requester
154          *
155          * @return array of owners
156          * @throws \Exception
157          */
158         public static function getContacts($owner, $rel, $module, $page = null, string $requester = null)
159         {
160                 $parameters = [
161                         'rel' => $rel,
162                         'uid' => $owner['uid'],
163                         'self' => false,
164                         'deleted' => false,
165                         'hidden' => false,
166                         'archive' => false,
167                         'pending' => false,
168                         'blocked' => false,
169                 ];
170
171                 $condition = DBA::mergeConditions($parameters, ["`url` IN (SELECT `url` FROM `apcontact`)"]);
172
173                 $total = DBA::count('contact', $condition);
174
175                 $modulePath = '/' . $module . '/';
176
177                 $data = ['@context' => ActivityPub::CONTEXT];
178                 $data['id'] = DI::baseUrl() . $modulePath . $owner['nickname'];
179                 $data['type'] = 'OrderedCollection';
180                 $data['totalItems'] = $total;
181
182                 // When we hide our friends we will only show the pure number but don't allow more.
183                 $show_contacts = empty($owner['hide-friends']);
184
185                 // Allow fetching the contact list when the requester is part of the list.
186                 if (($owner['page-flags'] == User::PAGE_FLAGS_PRVGROUP) && !empty($requester)) {
187                         $show_contacts = DBA::exists('contact', ['nurl' => Strings::normaliseLink($requester), 'rel' => $rel]);
188                 }
189
190                 if (!$show_contacts) {
191                         return $data;
192                 }
193
194                 if (empty($page)) {
195                         $data['first'] = DI::baseUrl() . $modulePath . $owner['nickname'] . '?page=1';
196                 } else {
197                         $data['type'] = 'OrderedCollectionPage';
198                         $list = [];
199
200                         $contacts = DBA::select('contact', ['url'], $condition, ['limit' => [($page - 1) * 100, 100]]);
201                         while ($contact = DBA::fetch($contacts)) {
202                                 $list[] = $contact['url'];
203                         }
204                         DBA::close($contacts);
205
206                         if (!empty($list)) {
207                                 $data['next'] = DI::baseUrl() . $modulePath . $owner['nickname'] . '?page=' . ($page + 1);
208                         }
209
210                         $data['partOf'] = DI::baseUrl() . $modulePath . $owner['nickname'];
211
212                         $data['orderedItems'] = $list;
213                 }
214
215                 return $data;
216         }
217
218         /**
219          * Public posts for the given owner
220          *
221          * @param array   $owner     Owner array
222          * @param integer $page      Page number
223          * @param string  $requester URL of requesting account
224          *
225          * @return array of posts
226          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
227          * @throws \ImagickException
228          */
229         public static function getOutbox($owner, $page = null, $requester = '')
230         {
231                 $condition = ['private' => [Item::PUBLIC, Item::UNLISTED]];
232
233                 if (!empty($requester)) {
234                         $requester_id = Contact::getIdForURL($requester, $owner['uid']);
235                         if (!empty($requester_id)) {
236                                 $permissionSets = DI::permissionSet()->selectByContactId($requester_id, $owner['uid']);
237                                 if (!empty($permissionSets)) {
238                                         $condition = ['psid' => array_merge($permissionSets->column('id'),
239                                                         [DI::permissionSet()->selectPublicForUser($owner['uid'])])];
240                                 }
241                         }
242                 }
243
244                 $condition = array_merge($condition,
245                         ['uid'           => $owner['uid'],
246                         'author-id'      => Contact::getIdForURL($owner['url'], 0, false),
247                         'gravity'        => [GRAVITY_PARENT, GRAVITY_COMMENT],
248                         'network'        => Protocol::FEDERATED,
249                         'parent-network' => Protocol::FEDERATED,
250                         'origin'         => true,
251                         'deleted'        => false,
252                         'visible'        => true]);
253
254                 $count = Post::count($condition);
255
256                 $data = ['@context' => ActivityPub::CONTEXT];
257                 $data['id'] = DI::baseUrl() . '/outbox/' . $owner['nickname'];
258                 $data['type'] = 'OrderedCollection';
259                 $data['totalItems'] = $count;
260
261                 if (empty($page)) {
262                         $data['first'] = DI::baseUrl() . '/outbox/' . $owner['nickname'] . '?page=1';
263                 } else {
264                         $data['type'] = 'OrderedCollectionPage';
265                         $list = [];
266
267                         $items = Post::select(['id'], $condition, ['limit' => [($page - 1) * 20, 20], 'order' => ['created' => true]]);
268                         while ($item = Post::fetch($items)) {
269                                 $activity = self::createActivityFromItem($item['id'], true);
270                                 $activity['type'] = $activity['type'] == 'Update' ? 'Create' : $activity['type'];
271
272                                 // Only list "Create" activity objects here, no reshares
273                                 if (!empty($activity['object']) && ($activity['type'] == 'Create')) {
274                                         $list[] = $activity['object'];
275                                 }
276                         }
277                         DBA::close($items);
278
279                         if (!empty($list)) {
280                                 $data['next'] = DI::baseUrl() . '/outbox/' . $owner['nickname'] . '?page=' . ($page + 1);
281                         }
282
283                         $data['partOf'] = DI::baseUrl() . '/outbox/' . $owner['nickname'];
284
285                         $data['orderedItems'] = $list;
286                 }
287
288                 return $data;
289         }
290
291         /**
292          * Return the service array containing information the used software and it's url
293          *
294          * @return array with service data
295          */
296         private static function getService()
297         {
298                 return ['type' => 'Service',
299                         'name' =>  FRIENDICA_PLATFORM . " '" . FRIENDICA_CODENAME . "' " . FRIENDICA_VERSION . '-' . DB_UPDATE_VERSION,
300                         'url' => DI::baseUrl()->get()];
301         }
302
303         /**
304          * Return the ActivityPub profile of the given user
305          *
306          * @param int $uid User ID
307          * @return array with profile data
308          * @throws HTTPException\NotFoundException
309          * @throws HTTPException\InternalServerErrorException
310          */
311         public static function getProfile(int $uid): array
312         {
313                 $owner = User::getOwnerDataById($uid);
314                 if (!isset($owner['id'])) {
315                         DI::logger()->error('Unable to find owner data for uid', ['uid' => $uid, 'callstack' => System::callstack(20)]);
316                         throw new HTTPException\NotFoundException('User not found.');
317                 }
318
319                 $data = ['@context' => ActivityPub::CONTEXT];
320                 $data['id'] = $owner['url'];
321
322                 if (!empty($owner['guid'])) {
323                         $data['diaspora:guid'] = $owner['guid'];
324                 }
325
326                 $data['type'] = ActivityPub::ACCOUNT_TYPES[$owner['account-type']];
327
328                 if ($uid != 0) {
329                         $data['following'] = DI::baseUrl() . '/following/' . $owner['nick'];
330                         $data['followers'] = DI::baseUrl() . '/followers/' . $owner['nick'];
331                         $data['inbox'] = DI::baseUrl() . '/inbox/' . $owner['nick'];
332                         $data['outbox'] = DI::baseUrl() . '/outbox/' . $owner['nick'];
333                 } else {
334                         $data['inbox'] = DI::baseUrl() . '/friendica/inbox';
335                 }
336
337                 $data['preferredUsername'] = $owner['nick'];
338                 $data['name'] = $owner['name'];
339
340                 if (!empty($owner['country-name'] . $owner['region'] . $owner['locality'])) {
341                         $data['vcard:hasAddress'] = ['@type' => 'vcard:Home', 'vcard:country-name' => $owner['country-name'],
342                                 'vcard:region' => $owner['region'], 'vcard:locality' => $owner['locality']];
343                 }
344
345                 if (!empty($owner['about'])) {
346                         $data['summary'] = BBCode::convertForUriId($owner['uri-id'] ?? 0, $owner['about'], BBCode::EXTERNAL);
347                 }
348
349                 if (!empty($owner['xmpp']) || !empty($owner['matrix'])) {
350                         $data['vcard:hasInstantMessage'] = [];
351
352                         if (!empty($owner['xmpp'])) {
353                                 $data['vcard:hasInstantMessage'][] = 'xmpp:' . $owner['xmpp'];
354                         }
355                         if (!empty($owner['matrix'])) {
356                                 $data['vcard:hasInstantMessage'][] = 'matrix:' . $owner['matrix'];
357                         }
358                 }
359
360                 $data['url'] = $owner['url'];
361                 $data['manuallyApprovesFollowers'] = in_array($owner['page-flags'], [User::PAGE_FLAGS_NORMAL, User::PAGE_FLAGS_PRVGROUP]);
362                 $data['discoverable'] = (bool)$owner['net-publish'];
363                 $data['publicKey'] = ['id' => $owner['url'] . '#main-key',
364                         'owner' => $owner['url'],
365                         'publicKeyPem' => $owner['pubkey']];
366                 $data['endpoints'] = ['sharedInbox' => DI::baseUrl() . '/inbox'];
367                 $data['icon'] = ['type' => 'Image', 'url' => User::getAvatarUrl($owner)];
368
369                 $resourceid = Photo::ridFromURI($owner['photo']);
370                 if (!empty($resourceid)) {
371                         $photo = Photo::selectFirst(['type'], ["resource-id" => $resourceid]);
372                         if (!empty($photo['type'])) {
373                                 $data['icon']['mediaType'] = $photo['type'];
374                         }
375                 }
376
377                 if (!empty($owner['header'])) {
378                         $data['image'] = ['type' => 'Image', 'url' => Contact::getHeaderUrlForId($owner['id'], '', $owner['updated'])];
379
380                         $resourceid = Photo::ridFromURI($owner['header']);
381                         if (!empty($resourceid)) {
382                                 $photo = Photo::selectFirst(['type'], ["resource-id" => $resourceid]);
383                                 if (!empty($photo['type'])) {
384                                         $data['image']['mediaType'] = $photo['type'];
385                                 }
386                         }
387                 }
388
389                 $custom_fields = [];
390
391                 foreach (DI::profileField()->selectByContactId(0, $uid) as $profile_field) {
392                         $custom_fields[] = [
393                                 'type' => 'PropertyValue',
394                                 'name' => $profile_field->label,
395                                 'value' => BBCode::convertForUriId($owner['uri-id'], $profile_field->value)
396                         ];
397                 };
398
399                 if (!empty($custom_fields)) {
400                         $data['attachment'] = $custom_fields;
401                 }
402
403                 $data['generator'] = self::getService();
404
405                 // tags: https://kitty.town/@inmysocks/100656097926961126.json
406                 return $data;
407         }
408
409         /**
410          * @param string $username
411          * @return array
412          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
413          */
414         public static function getDeletedUser($username)
415         {
416                 return [
417                         '@context' => ActivityPub::CONTEXT,
418                         'id' => DI::baseUrl() . '/profile/' . $username,
419                         'type' => 'Tombstone',
420                         'published' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
421                         'updated' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
422                         'deleted' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
423                 ];
424         }
425
426         /**
427          * Returns an array with permissions of a given item array
428          *
429          * @param array $item
430          *
431          * @return array with permissions
432          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
433          * @throws \ImagickException
434          */
435         private static function fetchPermissionBlockFromConversation($item)
436         {
437                 if (empty($item['thr-parent'])) {
438                         return [];
439                 }
440
441                 $condition = ['item-uri' => $item['thr-parent'], 'protocol' => Conversation::PARCEL_ACTIVITYPUB];
442                 $conversation = DBA::selectFirst('conversation', ['source'], $condition);
443                 if (!DBA::isResult($conversation)) {
444                         return [];
445                 }
446
447                 $permissions = [
448                         'to' => [],
449                         'cc' => [],
450                         'bto' => [],
451                         'bcc' => [],
452                 ];
453
454                 $activity = json_decode($conversation['source'], true);
455
456                 $actor = JsonLD::fetchElement($activity, 'actor', 'id');
457                 if (!empty($actor)) {
458                         $permissions['to'][] = $actor;
459                         $profile = APContact::getByURL($actor);
460                 } else {
461                         $profile = [];
462                 }
463
464                 $item_profile = APContact::getByURL($item['author-link']);
465                 $exclude[] = $item['author-link'];
466
467                 if ($item['gravity'] == GRAVITY_PARENT) {
468                         $exclude[] = $item['owner-link'];
469                 }
470
471                 foreach (['to', 'cc', 'bto', 'bcc'] as $element) {
472                         if (empty($activity[$element])) {
473                                 continue;
474                         }
475                         if (is_string($activity[$element])) {
476                                 $activity[$element] = [$activity[$element]];
477                         }
478
479                         foreach ($activity[$element] as $receiver) {
480                                 if (empty($receiver)) {
481                                         continue;
482                                 }
483
484                                 if (!empty($profile['followers']) && $receiver == $profile['followers'] && !empty($item_profile['followers'])) {
485                                         $permissions[$element][] = $item_profile['followers'];
486                                 } elseif (!in_array($receiver, $exclude)) {
487                                         $permissions[$element][] = $receiver;
488                                 }
489                         }
490                 }
491                 return $permissions;
492         }
493
494         /**
495          * Check if the given item id is from ActivityPub
496          *
497          * @param integer $item_id
498          * @return boolean "true" if the post is from ActivityPub
499          */
500         private static function isAPPost(int $item_id)
501         {
502                 if (empty($item_id)) {
503                         return false;
504                 }
505
506                 return Post::exists(['id' => $item_id, 'network' => Protocol::ACTIVITYPUB]);
507         }
508
509         /**
510          * Creates an array of permissions from an item thread
511          *
512          * @param array   $item       Item array
513          * @param boolean $blindcopy  addressing via "bcc" or "cc"?
514          * @param integer $last_id    Last item id for adding receivers
515          * @param boolean $forum_mode "true" means that we are sending content to a forum
516          *
517          * @return array with permission data
518          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
519          * @throws \ImagickException
520          */
521         private static function createPermissionBlockForItem($item, $blindcopy, $last_id = 0, $forum_mode = false)
522         {
523                 if ($last_id == 0) {
524                         $last_id = $item['id'];
525                 }
526
527                 $always_bcc = false;
528
529                 // Check if we should always deliver our stuff via BCC
530                 if (!empty($item['uid'])) {
531                         $profile = User::getOwnerDataById($item['uid']);
532                         if (!empty($profile)) {
533                                 $always_bcc = $profile['hide-friends'];
534                         }
535                 }
536
537                 if (DI::config()->get('system', 'ap_always_bcc')) {
538                         $always_bcc = true;
539                 }
540
541                 if (self::isAnnounce($item) || DI::config()->get('debug', 'total_ap_delivery') || self::isAPPost($last_id)) {
542                         // Will be activated in a later step
543                         $networks = Protocol::FEDERATED;
544                 } else {
545                         // For now only send to these contacts:
546                         $networks = [Protocol::ACTIVITYPUB, Protocol::OSTATUS];
547                 }
548
549                 $data = ['to' => [], 'cc' => [], 'bcc' => []];
550
551                 if ($item['gravity'] == GRAVITY_PARENT) {
552                         $actor_profile = APContact::getByURL($item['owner-link']);
553                 } else {
554                         $actor_profile = APContact::getByURL($item['author-link']);
555                 }
556
557                 $exclusive = false;
558
559                 $terms = Tag::getByURIId($item['uri-id'], [Tag::MENTION, Tag::IMPLICIT_MENTION, Tag::EXCLUSIVE_MENTION]);
560
561                 if ($item['private'] != Item::PRIVATE) {
562                         // Directly mention the original author upon a quoted reshare.
563                         // Else just ensure that the original author receives the reshare.
564                         $announce = self::getAnnounceArray($item);
565                         if (!empty($announce['comment'])) {
566                                 $data['to'][] = $announce['actor']['url'];
567                         } elseif (!empty($announce)) {
568                                 $data['cc'][] = $announce['actor']['url'];
569                         }
570
571                         $data = array_merge($data, self::fetchPermissionBlockFromConversation($item));
572
573                         // Check if the item is completely public or unlisted
574                         if ($item['private'] == Item::PUBLIC) {
575                                 $data['to'][] = ActivityPub::PUBLIC_COLLECTION;
576                         } else {
577                                 $data['cc'][] = ActivityPub::PUBLIC_COLLECTION;
578                         }
579
580                         foreach ($terms as $term) {
581                                 $profile = APContact::getByURL($term['url'], false);
582                                 if (!empty($profile)) {
583                                         if ($term['type'] == Tag::EXCLUSIVE_MENTION) {
584                                                 $exclusive = true;
585                                                 if (!empty($profile['followers']) && ($profile['type'] == 'Group')) {
586                                                         $data['cc'][] = $profile['followers'];
587                                                 }
588                                         }
589                                         $data['to'][] = $profile['url'];
590                                 }
591                         }
592                 } else {
593                         $receiver_list = Item::enumeratePermissions($item, true);
594
595                         foreach ($terms as $term) {
596                                 $cid = Contact::getIdForURL($term['url'], $item['uid']);
597                                 if (!empty($cid) && in_array($cid, $receiver_list)) {
598                                         $contact = DBA::selectFirst('contact', ['url', 'network', 'protocol', 'gsid'], ['id' => $cid, 'network' => Protocol::FEDERATED]);
599                                         if (!DBA::isResult($contact) || !self::isAPContact($contact, $networks)) {
600                                                 continue;
601                                         }
602
603                                         if (!empty($profile = APContact::getByURL($contact['url'], false))) {
604                                                 $data['to'][] = $profile['url'];
605                                         }
606                                 }
607                         }
608
609                         foreach ($receiver_list as $receiver) {
610                                 $contact = DBA::selectFirst('contact', ['url', 'hidden', 'network', 'protocol', 'gsid'], ['id' => $receiver, 'network' => Protocol::FEDERATED]);
611                                 if (!DBA::isResult($contact) || !self::isAPContact($contact, $networks)) {
612                                         continue;
613                                 }
614
615                                 if (!empty($profile = APContact::getByURL($contact['url'], false))) {
616                                         if ($contact['hidden'] || $always_bcc) {
617                                                 $data['bcc'][] = $profile['url'];
618                                         } else {
619                                                 $data['cc'][] = $profile['url'];
620                                         }
621                                 }
622                         }
623                 }
624
625                 if (!empty($item['parent'])) {
626                         $parents = Post::select(['id', 'author-link', 'owner-link', 'gravity', 'uri'], ['parent' => $item['parent']]);
627                         while ($parent = Post::fetch($parents)) {
628                                 if ($parent['gravity'] == GRAVITY_PARENT) {
629                                         $profile = APContact::getByURL($parent['owner-link'], false);
630                                         if (!empty($profile)) {
631                                                 if ($item['gravity'] != GRAVITY_PARENT) {
632                                                         // Comments to forums are directed to the forum
633                                                         // But comments to forums aren't directed to the followers collection
634                                                         // This rule is only valid when the actor isn't the forum.
635                                                         // The forum needs to transmit their content to their followers.
636                                                         if (($profile['type'] == 'Group') && ($profile['url'] != ($actor_profile['url'] ?? ''))) {
637                                                                 $data['to'][] = $profile['url'];
638                                                         } else {
639                                                                 $data['cc'][] = $profile['url'];
640                                                                 if (($item['private'] != Item::PRIVATE) && !empty($actor_profile['followers'])) {
641                                                                         $data['cc'][] = $actor_profile['followers'];
642                                                                 }
643                                                         }
644                                                 } elseif (!$exclusive) {
645                                                         // Public thread parent post always are directed to the followers.
646                                                         // This mustn't be done by posts that are directed to forum servers via the exclusive mention.
647                                                         // But possibly in that case we could add the "followers" collection of the forum to the message.
648                                                         if (($item['private'] != Item::PRIVATE) && !$forum_mode) {
649                                                                 $data['cc'][] = $actor_profile['followers'];
650                                                         }
651                                                 }
652                                         }
653                                 }
654
655                                 // Don't include data from future posts
656                                 if ($parent['id'] >= $last_id) {
657                                         continue;
658                                 }
659
660                                 $profile = APContact::getByURL($parent['author-link'], false);
661                                 if (!empty($profile)) {
662                                         if (($profile['type'] == 'Group') || ($parent['uri'] == $item['thr-parent'])) {
663                                                 $data['to'][] = $profile['url'];
664                                         } else {
665                                                 $data['cc'][] = $profile['url'];
666                                         }
667                                 }
668                         }
669                         DBA::close($parents);
670                 }
671
672                 $data['to'] = array_unique($data['to']);
673                 $data['cc'] = array_unique($data['cc']);
674                 $data['bcc'] = array_unique($data['bcc']);
675
676                 if (($key = array_search($item['author-link'], $data['to'])) !== false) {
677                         unset($data['to'][$key]);
678                 }
679
680                 if (($key = array_search($item['author-link'], $data['cc'])) !== false) {
681                         unset($data['cc'][$key]);
682                 }
683
684                 if (($key = array_search($item['author-link'], $data['bcc'])) !== false) {
685                         unset($data['bcc'][$key]);
686                 }
687
688                 foreach ($data['to'] as $to) {
689                         if (($key = array_search($to, $data['cc'])) !== false) {
690                                 unset($data['cc'][$key]);
691                         }
692
693                         if (($key = array_search($to, $data['bcc'])) !== false) {
694                                 unset($data['bcc'][$key]);
695                         }
696                 }
697
698                 foreach ($data['cc'] as $cc) {
699                         if (($key = array_search($cc, $data['bcc'])) !== false) {
700                                 unset($data['bcc'][$key]);
701                         }
702                 }
703
704                 $receivers = ['to' => array_values($data['to']), 'cc' => array_values($data['cc']), 'bcc' => array_values($data['bcc'])];
705
706                 if (!$blindcopy) {
707                         unset($receivers['bcc']);
708                 }
709
710                 return $receivers;
711         }
712
713         /**
714          * Check if an inbox is archived
715          *
716          * @param string $url Inbox url
717          *
718          * @return boolean "true" if inbox is archived
719          */
720         public static function archivedInbox($url)
721         {
722                 return DBA::exists('inbox-status', ['url' => $url, 'archive' => true]);
723         }
724
725         /**
726          * Check if a given contact should be delivered via AP
727          *
728          * @param array $contact
729          * @param array $networks
730          * @return bool
731          * @throws Exception
732          */
733         private static function isAPContact(array $contact, array $networks)
734         {
735                 if (in_array($contact['network'], $networks) || ($contact['protocol'] == Protocol::ACTIVITYPUB)) {
736                         return true;
737                 }
738
739                 return GServer::getProtocol($contact['gsid'] ?? 0) == Post\DeliveryData::ACTIVITYPUB;
740         }
741
742         /**
743          * Fetches a list of inboxes of followers of a given user
744          *
745          * @param integer $uid      User ID
746          * @param boolean $personal fetch personal inboxes
747          * @param boolean $all_ap   Retrieve all AP enabled inboxes
748          *
749          * @return array of follower inboxes
750          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
751          * @throws \ImagickException
752          */
753         public static function fetchTargetInboxesforUser($uid, $personal = false, bool $all_ap = false)
754         {
755                 $inboxes = [];
756
757                 $isforum = false;
758
759                 if (!empty($item['uid'])) {
760                         $profile = User::getOwnerDataById($item['uid']);
761                         if (!empty($profile)) {
762                                 $isforum = $profile['account-type'] == User::ACCOUNT_TYPE_COMMUNITY;
763                         }
764                 }
765
766                 if (DI::config()->get('debug', 'total_ap_delivery') || $all_ap) {
767                         // Will be activated in a later step
768                         $networks = Protocol::FEDERATED;
769                 } else {
770                         // For now only send to these contacts:
771                         $networks = [Protocol::ACTIVITYPUB, Protocol::OSTATUS];
772                 }
773
774                 $condition = ['uid' => $uid, 'archive' => false, 'pending' => false, 'blocked' => false, 'network' => Protocol::FEDERATED];
775
776                 if (!empty($uid)) {
777                         $condition['rel'] = [Contact::FOLLOWER, Contact::FRIEND];
778                 }
779
780                 $contacts = DBA::select('contact', ['id', 'url', 'network', 'protocol', 'gsid'], $condition);
781                 while ($contact = DBA::fetch($contacts)) {
782                         if (!self::isAPContact($contact, $networks)) {
783                                 continue;
784                         }
785
786                         if ($isforum && ($contact['network'] == Protocol::DFRN)) {
787                                 continue;
788                         }
789
790                         if (Network::isUrlBlocked($contact['url'])) {
791                                 continue;
792                         }
793
794                         $profile = APContact::getByURL($contact['url'], false);
795                         if (!empty($profile)) {
796                                 if (empty($profile['sharedinbox']) || $personal || Contact::isLocal($contact['url'])) {
797                                         $target = $profile['inbox'];
798                                 } else {
799                                         $target = $profile['sharedinbox'];
800                                 }
801                                 if (!self::archivedInbox($target)) {
802                                         $inboxes[$target][] = $contact['id'];
803                                 }
804                         }
805                 }
806                 DBA::close($contacts);
807
808                 return $inboxes;
809         }
810
811         /**
812          * Fetches an array of inboxes for the given item and user
813          *
814          * @param array   $item       Item array
815          * @param integer $uid        User ID
816          * @param boolean $personal   fetch personal inboxes
817          * @param integer $last_id    Last item id for adding receivers
818          * @param boolean $forum_mode "true" means that we are sending content to a forum
819          * @return array with inboxes
820          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
821          * @throws \ImagickException
822          */
823         public static function fetchTargetInboxes($item, $uid, $personal = false, $last_id = 0, $forum_mode = false)
824         {
825                 $permissions = self::createPermissionBlockForItem($item, true, $last_id, $forum_mode);
826                 if (empty($permissions)) {
827                         return [];
828                 }
829
830                 $inboxes = [];
831
832                 if ($item['gravity'] == GRAVITY_ACTIVITY) {
833                         $item_profile = APContact::getByURL($item['author-link'], false);
834                 } else {
835                         $item_profile = APContact::getByURL($item['owner-link'], false);
836                 }
837
838                 if (empty($item_profile)) {
839                         return [];
840                 }
841
842                 $profile_uid = User::getIdForURL($item_profile['url']);
843
844                 foreach (['to', 'cc', 'bto', 'bcc'] as $element) {
845                         if (empty($permissions[$element])) {
846                                 continue;
847                         }
848
849                         $blindcopy = in_array($element, ['bto', 'bcc']);
850
851                         foreach ($permissions[$element] as $receiver) {
852                                 if (empty($receiver) || Network::isUrlBlocked($receiver)) {
853                                         continue;
854                                 }
855
856                                 if ($item_profile && ($receiver == $item_profile['followers']) && ($uid == $profile_uid)) {
857                                         $inboxes = array_merge($inboxes, self::fetchTargetInboxesforUser($uid, $personal, self::isAPPost($last_id)));
858                                 } else {
859                                         $profile = APContact::getByURL($receiver, false);
860                                         if (!empty($profile)) {
861                                                 $contact = Contact::getByURLForUser($receiver, $uid, false, ['id']);
862
863                                                 if (empty($profile['sharedinbox']) || $personal || $blindcopy || Contact::isLocal($receiver)) {
864                                                         $target = $profile['inbox'];
865                                                 } else {
866                                                         $target = $profile['sharedinbox'];
867                                                 }
868                                                 if (!self::archivedInbox($target)) {
869                                                         $inboxes[$target][] = $contact['id'] ?? 0;
870                                                 }
871                                         }
872                                 }
873                         }
874                 }
875
876                 return $inboxes;
877         }
878
879         /**
880          * Creates an array in the structure of the item table for a given mail id
881          *
882          * @param integer $mail_id
883          *
884          * @return array
885          * @throws \Exception
886          */
887         public static function ItemArrayFromMail($mail_id, $use_title = false)
888         {
889                 $mail = DBA::selectFirst('mail', [], ['id' => $mail_id]);
890                 if (!DBA::isResult($mail)) {
891                         return [];
892                 }
893
894                 $reply = DBA::selectFirst('mail', ['uri', 'uri-id', 'from-url'], ['parent-uri' => $mail['parent-uri'], 'reply' => false]);
895                 if (!DBA::isResult($reply)) {
896                         $reply = $mail;
897                 }
898
899                 // Making the post more compatible for Mastodon by:
900                 // - Making it a note and not an article (no title)
901                 // - Moving the title into the "summary" field that is used as a "content warning"
902
903                 if (!$use_title) {
904                         $mail['body']         = '[abstract]' . $mail['title'] . "[/abstract]\n" . $mail['body'];
905                         $mail['title']        = '';
906                 }
907
908                 $mail['author-link']      = $mail['owner-link'] = $mail['from-url'];
909                 $mail['owner-id']         = $mail['author-id'];
910                 $mail['allow_cid']        = '<'.$mail['contact-id'].'>';
911                 $mail['allow_gid']        = '';
912                 $mail['deny_cid']         = '';
913                 $mail['deny_gid']         = '';
914                 $mail['private']          = Item::PRIVATE;
915                 $mail['deleted']          = false;
916                 $mail['edited']           = $mail['created'];
917                 $mail['plink']            = DI::baseUrl() . '/message/' . $mail['id'];
918                 $mail['parent-uri']       = $reply['uri'];
919                 $mail['parent-uri-id']    = $reply['uri-id'];
920                 $mail['parent-author-id'] = Contact::getIdForURL($reply['from-url'], 0, false);
921                 $mail['gravity']          = ($mail['reply'] ? GRAVITY_COMMENT: GRAVITY_PARENT);
922                 $mail['event-type']       = '';
923                 $mail['language']         = '';
924                 $mail['parent']           = 0;
925
926                 return $mail;
927         }
928
929         /**
930          * Creates an activity array for a given mail id
931          *
932          * @param integer $mail_id
933          * @param boolean $object_mode Is the activity item is used inside another object?
934          *
935          * @return array of activity
936          * @throws \Exception
937          */
938         public static function createActivityFromMail($mail_id, $object_mode = false)
939         {
940                 $mail = self::ItemArrayFromMail($mail_id);
941                 if (empty($mail)) {
942                         return [];
943                 }
944                 $object = self::createNote($mail);
945
946                 if (!$object_mode) {
947                         $data = ['@context' => ActivityPub::CONTEXT];
948                 } else {
949                         $data = [];
950                 }
951
952                 $data['id'] = $mail['uri'] . '/Create';
953                 $data['type'] = 'Create';
954                 $data['actor'] = $mail['author-link'];
955                 $data['published'] = DateTimeFormat::utc($mail['created'] . '+00:00', DateTimeFormat::ATOM);
956                 $data['instrument'] = self::getService();
957                 $data = array_merge($data, self::createPermissionBlockForItem($mail, true));
958
959                 if (empty($data['to']) && !empty($data['cc'])) {
960                         $data['to'] = $data['cc'];
961                 }
962
963                 if (empty($data['to']) && !empty($data['bcc'])) {
964                         $data['to'] = $data['bcc'];
965                 }
966
967                 unset($data['cc']);
968                 unset($data['bcc']);
969
970                 $object['to'] = $data['to'];
971                 $object['tag'] = [['type' => 'Mention', 'href' => $object['to'][0], 'name' => '']];
972
973                 unset($object['cc']);
974                 unset($object['bcc']);
975
976                 $data['directMessage'] = true;
977
978                 $data['object'] = $object;
979
980                 $owner = User::getOwnerDataById($mail['uid']);
981
982                 if (!$object_mode && !empty($owner)) {
983                         return LDSignature::sign($data, $owner);
984                 } else {
985                         return $data;
986                 }
987         }
988
989         /**
990          * Returns the activity type of a given item
991          *
992          * @param array $item
993          *
994          * @return string with activity type
995          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
996          * @throws \ImagickException
997          */
998         private static function getTypeOfItem($item)
999         {
1000                 $reshared = false;
1001
1002                 // Only check for a reshare, if it is a real reshare and no quoted reshare
1003                 if (strpos($item['body'], "[share") === 0) {
1004                         $announce = self::getAnnounceArray($item);
1005                         $reshared = !empty($announce);
1006                 }
1007
1008                 if ($reshared) {
1009                         $type = 'Announce';
1010                 } elseif ($item['verb'] == Activity::POST) {
1011                         if ($item['created'] == $item['edited']) {
1012                                 $type = 'Create';
1013                         } else {
1014                                 $type = 'Update';
1015                         }
1016                 } elseif ($item['verb'] == Activity::LIKE) {
1017                         $type = 'Like';
1018                 } elseif ($item['verb'] == Activity::DISLIKE) {
1019                         $type = 'Dislike';
1020                 } elseif ($item['verb'] == Activity::ATTEND) {
1021                         $type = 'Accept';
1022                 } elseif ($item['verb'] == Activity::ATTENDNO) {
1023                         $type = 'Reject';
1024                 } elseif ($item['verb'] == Activity::ATTENDMAYBE) {
1025                         $type = 'TentativeAccept';
1026                 } elseif ($item['verb'] == Activity::FOLLOW) {
1027                         $type = 'Follow';
1028                 } elseif ($item['verb'] == Activity::TAG) {
1029                         $type = 'Add';
1030                 } elseif ($item['verb'] == Activity::ANNOUNCE) {
1031                         $type = 'Announce';
1032                 } else {
1033                         $type = '';
1034                 }
1035
1036                 return $type;
1037         }
1038
1039         /**
1040          * Creates the activity or fetches it from the cache
1041          *
1042          * @param integer $item_id
1043          * @param boolean $force Force new cache entry
1044          *
1045          * @return array with the activity
1046          * @throws \Exception
1047          */
1048         public static function createCachedActivityFromItem($item_id, $force = false)
1049         {
1050                 $cachekey = 'APDelivery:createActivity:' . $item_id;
1051
1052                 if (!$force) {
1053                         $data = DI::cache()->get($cachekey);
1054                         if (!is_null($data)) {
1055                                 return $data;
1056                         }
1057                 }
1058
1059                 $data = self::createActivityFromItem($item_id);
1060
1061                 DI::cache()->set($cachekey, $data, Duration::QUARTER_HOUR);
1062                 return $data;
1063         }
1064
1065         /**
1066          * Creates an activity array for a given item id
1067          *
1068          * @param integer $item_id
1069          * @param boolean $object_mode Is the activity item is used inside another object?
1070          *
1071          * @return false|array
1072          * @throws \Exception
1073          */
1074         public static function createActivityFromItem(int $item_id, bool $object_mode = false)
1075         {
1076                 Logger::info('Fetching activity', ['item' => $item_id]);
1077                 $item = Post::selectFirst(Item::DELIVER_FIELDLIST, ['id' => $item_id, 'parent-network' => Protocol::NATIVE_SUPPORT]);
1078                 if (!DBA::isResult($item)) {
1079                         return false;
1080                 }
1081
1082                 // In case of a forum post ensure to return the original post if author and forum are on the same machine
1083                 if (($item['gravity'] == GRAVITY_PARENT) && !empty($item['forum_mode'])) {
1084                         $author = Contact::getById($item['author-id'], ['nurl']);
1085                         if (!empty($author['nurl'])) {
1086                                 $self = Contact::selectFirst(['uid'], ['nurl' => $author['nurl'], 'self' => true]);
1087                                 if (!empty($self['uid'])) {
1088                                         $forum_item = Post::selectFirst(Item::DELIVER_FIELDLIST, ['uri-id' => $item['uri-id'], 'uid' => $self['uid']]);
1089                                         if (DBA::isResult($forum_item)) {
1090                                                 $item = $forum_item;
1091                                         }
1092                                 }
1093                         }
1094                 }
1095
1096                 if (empty($item['uri-id'])) {
1097                         Logger::warning('Item without uri-id', ['item' => $item]);
1098                         return false;
1099                 }
1100
1101                 if (!$item['deleted']) {
1102                         $condition = ['item-uri' => $item['uri'], 'protocol' => Conversation::PARCEL_ACTIVITYPUB];
1103                         $conversation = DBA::selectFirst('conversation', ['source'], $condition);
1104                         if (!$item['origin'] && DBA::isResult($conversation)) {
1105                                 $data = json_decode($conversation['source'], true);
1106                                 if (!empty($data['type'])) {
1107                                         if (in_array($data['type'], ['Create', 'Update'])) {
1108                                                 if ($object_mode) {
1109                                                         unset($data['@context']);
1110                                                         unset($data['signature']);
1111                                                 }
1112                                                 Logger::info('Return stored conversation', ['item' => $item_id]);
1113                                                 return $data;
1114                                         } elseif (in_array('as:' . $data['type'], Receiver::CONTENT_TYPES)) {
1115                                                 if (!empty($data['@context'])) {
1116                                                         $context = $data['@context'];
1117                                                         unset($data['@context']);
1118                                                 }
1119                                                 unset($data['actor']);
1120                                                 $object = $data;
1121                                         }
1122                                 }
1123                         }
1124                 }
1125
1126                 $type = self::getTypeOfItem($item);
1127
1128                 if (!$object_mode) {
1129                         $data = ['@context' => $context ?? ActivityPub::CONTEXT];
1130
1131                         if ($item['deleted'] && ($item['gravity'] == GRAVITY_ACTIVITY)) {
1132                                 $type = 'Undo';
1133                         } elseif ($item['deleted']) {
1134                                 $type = 'Delete';
1135                         }
1136                 } else {
1137                         $data = [];
1138                 }
1139
1140                 if ($type == 'Delete') {
1141                         $data['id'] = Item::newURI($item['uid'], $item['guid']) . '/' . $type;;
1142                 } elseif (($item['gravity'] == GRAVITY_ACTIVITY) && ($type != 'Undo')) {
1143                         $data['id'] = $item['uri'];
1144                 } else {
1145                         $data['id'] = $item['uri'] . '/' . $type;
1146                 }
1147
1148                 $data['type'] = $type;
1149
1150                 if (($type != 'Announce') || ($item['gravity'] != GRAVITY_PARENT)) {
1151                         $data['actor'] = $item['author-link'];
1152                 } else {
1153                         $data['actor'] = $item['owner-link'];
1154                 }
1155
1156                 $data['published'] = DateTimeFormat::utc($item['created'] . '+00:00', DateTimeFormat::ATOM);
1157
1158                 $data['instrument'] = self::getService();
1159
1160                 $data = array_merge($data, self::createPermissionBlockForItem($item, false));
1161
1162                 if (in_array($data['type'], ['Create', 'Update', 'Delete'])) {
1163                         $data['object'] = $object ?? self::createNote($item);
1164                 } elseif ($data['type'] == 'Add') {
1165                         $data = self::createAddTag($item, $data);
1166                 } elseif ($data['type'] == 'Announce') {
1167                         if ($item['verb'] == ACTIVITY::ANNOUNCE) {
1168                                 $data['object'] = $item['thr-parent'];
1169                         } else {
1170                                 $data = self::createAnnounce($item, $data);
1171                         }
1172                 } elseif ($data['type'] == 'Follow') {
1173                         $data['object'] = $item['parent-uri'];
1174                 } elseif ($data['type'] == 'Undo') {
1175                         $data['object'] = self::createActivityFromItem($item_id, true);
1176                 } else {
1177                         $data['diaspora:guid'] = $item['guid'];
1178                         if (!empty($item['signed_text'])) {
1179                                 $data['diaspora:like'] = $item['signed_text'];
1180                         }
1181                         $data['object'] = $item['thr-parent'];
1182                 }
1183
1184                 if (!empty($item['contact-uid'])) {
1185                         $uid = $item['contact-uid'];
1186                 } else {
1187                         $uid = $item['uid'];
1188                 }
1189
1190                 $owner = User::getOwnerDataById($uid);
1191
1192                 Logger::info('Fetched activity', ['item' => $item_id, 'uid' => $uid]);
1193
1194                 // We don't sign if we aren't the actor. This is important for relaying content especially for forums
1195                 if (!$object_mode && !empty($owner) && ($data['actor'] == $owner['url'])) {
1196                         return LDSignature::sign($data, $owner);
1197                 } else {
1198                         return $data;
1199                 }
1200
1201                 /// @todo Create "conversation" entry
1202         }
1203
1204         /**
1205          * Creates a location entry for a given item array
1206          *
1207          * @param array $item
1208          *
1209          * @return array with location array
1210          */
1211         private static function createLocation($item)
1212         {
1213                 $location = ['type' => 'Place'];
1214
1215                 if (!empty($item['location'])) {
1216                         $location['name'] = $item['location'];
1217                 }
1218
1219                 $coord = [];
1220
1221                 if (empty($item['coord'])) {
1222                         $coord = Map::getCoordinates($item['location']);
1223                 } else {
1224                         $coords = explode(' ', $item['coord']);
1225                         if (count($coords) == 2) {
1226                                 $coord = ['lat' => $coords[0], 'lon' => $coords[1]];
1227                         }
1228                 }
1229
1230                 if (!empty($coord['lat']) && !empty($coord['lon'])) {
1231                         $location['latitude'] = $coord['lat'];
1232                         $location['longitude'] = $coord['lon'];
1233                 }
1234
1235                 return $location;
1236         }
1237
1238         /**
1239          * Returns a tag array for a given item array
1240          *
1241          * @param array $item
1242          *
1243          * @return array of tags
1244          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1245          */
1246         private static function createTagList($item)
1247         {
1248                 $tags = [];
1249
1250                 $terms = Tag::getByURIId($item['uri-id'], [Tag::HASHTAG, Tag::MENTION, Tag::IMPLICIT_MENTION, Tag::EXCLUSIVE_MENTION]);
1251                 foreach ($terms as $term) {
1252                         if ($term['type'] == Tag::HASHTAG) {
1253                                 $url = DI::baseUrl() . '/search?tag=' . urlencode($term['name']);
1254                                 $tags[] = ['type' => 'Hashtag', 'href' => $url, 'name' => '#' . $term['name']];
1255                         } else {
1256                                 $contact = Contact::getByURL($term['url'], false, ['addr']);
1257                                 if (empty($contact)) {
1258                                         continue;
1259                                 }
1260                                 if (!empty($contact['addr'])) {
1261                                         $mention = '@' . $contact['addr'];
1262                                 } else {
1263                                         $mention = '@' . $term['url'];
1264                                 }
1265
1266                                 $tags[] = ['type' => 'Mention', 'href' => $term['url'], 'name' => $mention];
1267                         }
1268                 }
1269
1270                 $announce = self::getAnnounceArray($item);
1271                 // Mention the original author upon commented reshares
1272                 if (!empty($announce['comment'])) {
1273                         $tags[] = ['type' => 'Mention', 'href' => $announce['actor']['url'], 'name' => '@' . $announce['actor']['addr']];
1274                 }
1275
1276                 return $tags;
1277         }
1278
1279         /**
1280          * Adds attachment data to the JSON document
1281          *
1282          * @param array  $item Data of the item that is to be posted
1283          * @param string $type Object type
1284          *
1285          * @return array with attachment data
1286          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1287          */
1288         private static function createAttachmentList($item, $type)
1289         {
1290                 $attachments = [];
1291
1292                 $uriids = [$item['uri-id']];
1293                 $shared = BBCode::fetchShareAttributes($item['body']);
1294                 if (!empty($shared['guid'])) {
1295                         $shared_item = Post::selectFirst(['uri-id'], ['guid' => $shared['guid']]);
1296                         if (!empty($shared_item['uri-id'])) {
1297                                 $uriids[] = $shared_item['uri-id'];
1298                         }
1299                 }
1300
1301                 $urls = [];
1302                 foreach ($uriids as $uriid) {
1303                         foreach (Post\Media::getByURIId($uriid, [Post\Media::AUDIO, Post\Media::IMAGE, Post\Media::VIDEO, Post\Media::DOCUMENT, Post\Media::TORRENT]) as $attachment) {
1304                                 if (in_array($attachment['url'], $urls)) {
1305                                         continue;
1306                                 }
1307                                 $urls[] = $attachment['url'];
1308
1309                                 $attach = ['type' => 'Document',
1310                                         'mediaType' => $attachment['mimetype'],
1311                                         'url' => $attachment['url'],
1312                                         'name' => $attachment['description']];
1313
1314                                 if (!empty($attachment['height'])) {
1315                                         $attach['height'] = $attachment['height'];
1316                                 }
1317
1318                                 if (!empty($attachment['width'])) {
1319                                         $attach['width'] = $attachment['width'];
1320                                 }
1321
1322                                 if (!empty($attachment['preview'])) {
1323                                         $attach['image'] = $attachment['preview'];
1324                                 }
1325
1326                                 $attachments[] = $attach;
1327                         }
1328                 }
1329
1330                 return $attachments;
1331         }
1332
1333         /**
1334          * Callback function to replace a Friendica style mention in a mention for a summary
1335          *
1336          * @param array $match Matching values for the callback
1337          * @return string Replaced mention
1338          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1339          */
1340         private static function mentionAddrCallback($match)
1341         {
1342                 if (empty($match[1])) {
1343                         return '';
1344                 }
1345
1346                 $data = Contact::getByURL($match[1], false, ['addr']);
1347                 if (empty($data['addr'])) {
1348                         return $match[0];
1349                 }
1350
1351                 return '@' . $data['addr'];
1352         }
1353
1354         /**
1355          * Remove image elements since they are added as attachment
1356          *
1357          * @param string $body
1358          *
1359          * @return string with removed images
1360          */
1361         private static function removePictures($body)
1362         {
1363                 // Simplify image codes
1364                 $body = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '[img]$3[/img]', $body);
1365                 $body = preg_replace("/\[img\=(.*?)\](.*?)\[\/img\]/ism", '[img]$1[/img]', $body);
1366
1367                 // Now remove local links
1368                 $body = preg_replace_callback(
1369                         '/\[url=([^\[\]]*)\]\[img\](.*)\[\/img\]\[\/url\]/Usi',
1370                         function ($match) {
1371                                 // We remove the link when it is a link to a local photo page
1372                                 if (Photo::isLocalPage($match[1])) {
1373                                         return '';
1374                                 }
1375                                 // otherwise we just return the link
1376                                 return '[url]' . $match[1] . '[/url]';
1377                         },
1378                         $body
1379                 );
1380
1381                 // Remove all pictures
1382                 $body = preg_replace("/\[img\]([^\[\]]*)\[\/img\]/Usi", '', $body);
1383
1384                 return $body;
1385         }
1386
1387         /**
1388          * Fetches the "context" value for a givem item array from the "conversation" table
1389          *
1390          * @param array $item
1391          *
1392          * @return string with context url
1393          * @throws \Exception
1394          */
1395         private static function fetchContextURLForItem($item)
1396         {
1397                 $conversation = DBA::selectFirst('conversation', ['conversation-href', 'conversation-uri'], ['item-uri' => $item['parent-uri']]);
1398                 if (DBA::isResult($conversation) && !empty($conversation['conversation-href'])) {
1399                         $context_uri = $conversation['conversation-href'];
1400                 } elseif (DBA::isResult($conversation) && !empty($conversation['conversation-uri'])) {
1401                         $context_uri = $conversation['conversation-uri'];
1402                 } else {
1403                         $context_uri = $item['parent-uri'] . '#context';
1404                 }
1405                 return $context_uri;
1406         }
1407
1408         /**
1409          * Returns if the post contains sensitive content ("nsfw")
1410          *
1411          * @param integer $uri_id
1412          *
1413          * @return boolean
1414          * @throws \Exception
1415          */
1416         private static function isSensitive($uri_id)
1417         {
1418                 return DBA::exists('tag-view', ['uri-id' => $uri_id, 'name' => 'nsfw']);
1419         }
1420
1421         /**
1422          * Creates event data
1423          *
1424          * @param array $item
1425          *
1426          * @return array with the event data
1427          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1428          */
1429         private static function createEvent($item)
1430         {
1431                 $event = [];
1432                 $event['name'] = $item['event-summary'];
1433                 $event['content'] = BBCode::convertForUriId($item['uri-id'], $item['event-desc'], BBCode::ACTIVITYPUB);
1434                 $event['startTime'] = DateTimeFormat::utc($item['event-start'], 'c');
1435
1436                 if (!$item['event-nofinish']) {
1437                         $event['endTime'] = DateTimeFormat::utc($item['event-finish'], 'c');
1438                 }
1439
1440                 if (!empty($item['event-location'])) {
1441                         $item['location'] = $item['event-location'];
1442                         $event['location'] = self::createLocation($item);
1443                 }
1444
1445                 // 2021.12: Backward compatibility value, all the events now "adjust" to the viewer timezone
1446                 $event['dfrn:adjust'] = true;
1447
1448                 return $event;
1449         }
1450
1451         /**
1452          * Creates a note/article object array
1453          *
1454          * @param array $item
1455          *
1456          * @return array with the object data
1457          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1458          * @throws \ImagickException
1459          */
1460         public static function createNote($item)
1461         {
1462                 if (empty($item)) {
1463                         return [];
1464                 }
1465
1466                 if ($item['event-type'] == 'event') {
1467                         $type = 'Event';
1468                 } elseif (!empty($item['title'])) {
1469                         $type = 'Article';
1470                 } else {
1471                         $type = 'Note';
1472                 }
1473
1474                 if ($item['deleted']) {
1475                         $type = 'Tombstone';
1476                 }
1477
1478                 $data = [];
1479                 $data['id'] = $item['uri'];
1480                 $data['type'] = $type;
1481
1482                 if ($item['deleted']) {
1483                         return $data;
1484                 }
1485
1486                 $data['summary'] = BBCode::toPlaintext(BBCode::getAbstract($item['body'], Protocol::ACTIVITYPUB));
1487
1488                 if ($item['uri'] != $item['thr-parent']) {
1489                         $data['inReplyTo'] = $item['thr-parent'];
1490                 } else {
1491                         $data['inReplyTo'] = null;
1492                 }
1493
1494                 $data['diaspora:guid'] = $item['guid'];
1495                 $data['published'] = DateTimeFormat::utc($item['created'] . '+00:00', DateTimeFormat::ATOM);
1496
1497                 if ($item['created'] != $item['edited']) {
1498                         $data['updated'] = DateTimeFormat::utc($item['edited'] . '+00:00', DateTimeFormat::ATOM);
1499                 }
1500
1501                 $data['url'] = $item['plink'];
1502                 $data['attributedTo'] = $item['author-link'];
1503                 $data['sensitive'] = self::isSensitive($item['uri-id']);
1504                 $data['context'] = self::fetchContextURLForItem($item);
1505
1506                 if (!empty($item['title'])) {
1507                         $data['name'] = BBCode::toPlaintext($item['title'], false);
1508                 }
1509
1510                 $permission_block = self::createPermissionBlockForItem($item, false);
1511
1512                 $body = $item['body'];
1513
1514                 if ($type == 'Note') {
1515                         $body = $item['raw-body'] ?? self::removePictures($body);
1516                 }
1517
1518                 /**
1519                  * @todo Improve the automated summary
1520                  * This part is currently deactivated. The automated summary seems to be more
1521                  * confusing than helping. But possibly we will find a better way.
1522                  * So the code is left here for now as a reminder
1523                  *
1524                  * } elseif (($type == 'Article') && empty($data['summary'])) {
1525                  *              $regexp = "/[@!]\[url\=([^\[\]]*)\].*?\[\/url\]/ism";
1526                  *              $summary = preg_replace_callback($regexp, ['self', 'mentionAddrCallback'], $body);
1527                  *              $data['summary'] = BBCode::toPlaintext(Plaintext::shorten(self::removePictures($summary), 1000));
1528                  * }
1529                  */
1530
1531                 if (empty($item['uid']) || !Feature::isEnabled($item['uid'], 'explicit_mentions')) {
1532                         $body = self::prependMentions($body, $item['uri-id'], $item['author-link']);
1533                 }
1534
1535                 if ($type == 'Event') {
1536                         $data = array_merge($data, self::createEvent($item));
1537                 } else {
1538                         $body = BBCode::setMentionsToNicknames($body);
1539
1540                         $data['content'] = BBCode::convertForUriId($item['uri-id'], $body, BBCode::ACTIVITYPUB);
1541                 }
1542
1543                 // The regular "content" field does contain a minimized HTML. This is done since systems like
1544                 // Mastodon has got problems with - for example - embedded pictures.
1545                 // The contentMap does contain the unmodified HTML.
1546                 $language = self::getLanguage($item);
1547                 if (!empty($language)) {
1548                         $richbody = BBCode::setMentionsToNicknames($item['body'] ?? '');
1549                         $richbody = BBCode::removeAttachment($richbody);
1550
1551                         $data['contentMap'][$language] = BBCode::convertForUriId($item['uri-id'], $richbody, BBCode::EXTERNAL);
1552                 }
1553
1554                 $data['source'] = ['content' => $item['body'], 'mediaType' => "text/bbcode"];
1555
1556                 if (!empty($item['signed_text']) && ($item['uri'] != $item['thr-parent'])) {
1557                         $data['diaspora:comment'] = $item['signed_text'];
1558                 }
1559
1560                 $data['attachment'] = self::createAttachmentList($item, $type);
1561                 $data['tag'] = self::createTagList($item);
1562
1563                 if (empty($data['location']) && (!empty($item['coord']) || !empty($item['location']))) {
1564                         $data['location'] = self::createLocation($item);
1565                 }
1566
1567                 if (!empty($item['app'])) {
1568                         $data['generator'] = ['type' => 'Application', 'name' => $item['app']];
1569                 }
1570
1571                 $data = array_merge($data, $permission_block);
1572
1573                 return $data;
1574         }
1575
1576         /**
1577          * Fetches the language from the post, the user or the system.
1578          *
1579          * @param array $item
1580          *
1581          * @return string language string
1582          */
1583         private static function getLanguage(array $item)
1584         {
1585                 // Try to fetch the language from the post itself
1586                 if (!empty($item['language'])) {
1587                         $languages = array_keys(json_decode($item['language'], true));
1588                         if (!empty($languages[0])) {
1589                                 return $languages[0];
1590                         }
1591                 }
1592
1593                 // Otherwise use the user's language
1594                 if (!empty($item['uid'])) {
1595                         $user = DBA::selectFirst('user', ['language'], ['uid' => $item['uid']]);
1596                         if (!empty($user['language'])) {
1597                                 return $user['language'];
1598                         }
1599                 }
1600
1601                 // And finally just use the system language
1602                 return DI::config()->get('system', 'language');
1603         }
1604
1605         /**
1606          * Creates an an "add tag" entry
1607          *
1608          * @param array $item
1609          * @param array $data activity data
1610          *
1611          * @return array with activity data for adding tags
1612          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1613          * @throws \ImagickException
1614          */
1615         private static function createAddTag($item, $data)
1616         {
1617                 $object = XML::parseString($item['object']);
1618                 $target = XML::parseString($item["target"]);
1619
1620                 $data['diaspora:guid'] = $item['guid'];
1621                 $data['actor'] = $item['author-link'];
1622                 $data['target'] = (string)$target->id;
1623                 $data['summary'] = BBCode::toPlaintext($item['body']);
1624                 $data['object'] = ['id' => (string)$object->id, 'type' => 'tag', 'name' => (string)$object->title, 'content' => (string)$object->content];
1625
1626                 return $data;
1627         }
1628
1629         /**
1630          * Creates an announce object entry
1631          *
1632          * @param array $item
1633          * @param array $data activity data
1634          *
1635          * @return array with activity data
1636          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1637          * @throws \ImagickException
1638          */
1639         private static function createAnnounce($item, $data)
1640         {
1641                 $orig_body = $item['body'];
1642                 $announce = self::getAnnounceArray($item);
1643                 if (empty($announce)) {
1644                         $data['type'] = 'Create';
1645                         $data['object'] = self::createNote($item);
1646                         return $data;
1647                 }
1648
1649                 if (empty($announce['comment'])) {
1650                         // Pure announce, without a quote
1651                         $data['type'] = 'Announce';
1652                         $data['object'] = $announce['object']['uri'];
1653                         return $data;
1654                 }
1655
1656                 // Quote
1657                 $data['type'] = 'Create';
1658                 $item['body'] = $announce['comment'] . "\n" . $announce['object']['plink'];
1659                 $data['object'] = self::createNote($item);
1660
1661                 /// @todo Finally descide how to implement this in AP. This is a possible way:
1662                 $data['object']['attachment'][] = self::createNote($announce['object']);
1663
1664                 $data['object']['source']['content'] = $orig_body;
1665                 return $data;
1666         }
1667
1668         /**
1669          * Return announce related data if the item is an annunce
1670          *
1671          * @param array $item
1672          *
1673          * @return array
1674          */
1675         public static function getAnnounceArray($item)
1676         {
1677                 $reshared = Item::getShareArray($item);
1678                 if (empty($reshared['guid'])) {
1679                         return [];
1680                 }
1681
1682                 $reshared_item = Post::selectFirst(Item::DELIVER_FIELDLIST, ['guid' => $reshared['guid']]);
1683                 if (!DBA::isResult($reshared_item)) {
1684                         return [];
1685                 }
1686
1687                 if (!in_array($reshared_item['network'], [Protocol::ACTIVITYPUB, Protocol::DFRN])) {
1688                         return [];
1689                 }
1690
1691                 $profile = APContact::getByURL($reshared_item['author-link'], false);
1692                 if (empty($profile)) {
1693                         return [];
1694                 }
1695
1696                 return ['object' => $reshared_item, 'actor' => $profile, 'comment' => $reshared['comment']];
1697         }
1698
1699         /**
1700          * Checks if the provided item array is an announce
1701          *
1702          * @param array $item
1703          *
1704          * @return boolean
1705          */
1706         public static function isAnnounce($item)
1707         {
1708                 if (!empty($item['verb']) && ($item['verb'] == Activity::ANNOUNCE)) {
1709                         return true;
1710                 }
1711
1712                 $announce = self::getAnnounceArray($item);
1713                 if (empty($announce)) {
1714                         return false;
1715                 }
1716
1717                 return empty($announce['comment']);
1718         }
1719
1720         /**
1721          * Creates an activity id for a given contact id
1722          *
1723          * @param integer $cid Contact ID of target
1724          *
1725          * @return bool|string activity id
1726          */
1727         public static function activityIDFromContact($cid)
1728         {
1729                 $contact = DBA::selectFirst('contact', ['uid', 'id', 'created'], ['id' => $cid]);
1730                 if (!DBA::isResult($contact)) {
1731                         return false;
1732                 }
1733
1734                 $hash = hash('ripemd128', $contact['uid'].'-'.$contact['id'].'-'.$contact['created']);
1735                 $uuid = substr($hash, 0, 8). '-' . substr($hash, 8, 4) . '-' . substr($hash, 12, 4) . '-' . substr($hash, 16, 4) . '-' . substr($hash, 20, 12);
1736                 return DI::baseUrl() . '/activity/' . $uuid;
1737         }
1738
1739         /**
1740          * Transmits a contact suggestion to a given inbox
1741          *
1742          * @param integer $uid           User ID
1743          * @param string  $inbox         Target inbox
1744          * @param integer $suggestion_id Suggestion ID
1745          *
1746          * @return boolean was the transmission successful?
1747          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1748          */
1749         public static function sendContactSuggestion($uid, $inbox, $suggestion_id)
1750         {
1751                 $owner = User::getOwnerDataById($uid);
1752
1753                 $suggestion = DI::fsuggest()->selectOneById($suggestion_id);
1754
1755                 $data = ['@context' => ActivityPub::CONTEXT,
1756                         'id' => DI::baseUrl() . '/activity/' . System::createGUID(),
1757                         'type' => 'Announce',
1758                         'actor' => $owner['url'],
1759                         'object' => $suggestion->url,
1760                         'content' => $suggestion->note,
1761                         'instrument' => self::getService(),
1762                         'to' => [ActivityPub::PUBLIC_COLLECTION],
1763                         'cc' => []];
1764
1765                 $signed = LDSignature::sign($data, $owner);
1766
1767                 Logger::info('Deliver profile deletion for user ' . $uid . ' to ' . $inbox . ' via ActivityPub');
1768                 return HTTPSignature::transmit($signed, $inbox, $uid);
1769         }
1770
1771         /**
1772          * Transmits a profile relocation to a given inbox
1773          *
1774          * @param integer $uid   User ID
1775          * @param string  $inbox Target inbox
1776          *
1777          * @return boolean was the transmission successful?
1778          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1779          */
1780         public static function sendProfileRelocation($uid, $inbox)
1781         {
1782                 $owner = User::getOwnerDataById($uid);
1783
1784                 $data = ['@context' => ActivityPub::CONTEXT,
1785                         'id' => DI::baseUrl() . '/activity/' . System::createGUID(),
1786                         'type' => 'dfrn:relocate',
1787                         'actor' => $owner['url'],
1788                         'object' => $owner['url'],
1789                         'published' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
1790                         'instrument' => self::getService(),
1791                         'to' => [ActivityPub::PUBLIC_COLLECTION],
1792                         'cc' => []];
1793
1794                 $signed = LDSignature::sign($data, $owner);
1795
1796                 Logger::info('Deliver profile relocation for user ' . $uid . ' to ' . $inbox . ' via ActivityPub');
1797                 return HTTPSignature::transmit($signed, $inbox, $uid);
1798         }
1799
1800         /**
1801          * Transmits a profile deletion to a given inbox
1802          *
1803          * @param integer $uid   User ID
1804          * @param string  $inbox Target inbox
1805          *
1806          * @return boolean was the transmission successful?
1807          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1808          */
1809         public static function sendProfileDeletion($uid, $inbox)
1810         {
1811                 $owner = User::getOwnerDataById($uid);
1812
1813                 if (empty($owner)) {
1814                         Logger::error('No owner data found, the deletion message cannot be processed.', ['user' => $uid]);
1815                         return false;
1816                 }
1817
1818                 if (empty($owner['uprvkey'])) {
1819                         Logger::error('No private key for owner found, the deletion message cannot be processed.', ['user' => $uid]);
1820                         return false;
1821                 }
1822
1823                 $data = ['@context' => ActivityPub::CONTEXT,
1824                         'id' => DI::baseUrl() . '/activity/' . System::createGUID(),
1825                         'type' => 'Delete',
1826                         'actor' => $owner['url'],
1827                         'object' => $owner['url'],
1828                         'published' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
1829                         'instrument' => self::getService(),
1830                         'to' => [ActivityPub::PUBLIC_COLLECTION],
1831                         'cc' => []];
1832
1833                 $signed = LDSignature::sign($data, $owner);
1834
1835                 Logger::info('Deliver profile deletion for user ' . $uid . ' to ' . $inbox . ' via ActivityPub');
1836                 return HTTPSignature::transmit($signed, $inbox, $uid);
1837         }
1838
1839         /**
1840          * Transmits a profile change to a given inbox
1841          *
1842          * @param integer $uid   User ID
1843          * @param string  $inbox Target inbox
1844          *
1845          * @return boolean was the transmission successful?
1846          * @throws HTTPException\InternalServerErrorException
1847          * @throws HTTPException\NotFoundException
1848          * @throws \ImagickException
1849          */
1850         public static function sendProfileUpdate(int $uid, string $inbox): bool
1851         {
1852                 $owner = User::getOwnerDataById($uid);
1853                 $profile = APContact::getByURL($owner['url']);
1854
1855                 $data = ['@context' => ActivityPub::CONTEXT,
1856                         'id' => DI::baseUrl() . '/activity/' . System::createGUID(),
1857                         'type' => 'Update',
1858                         'actor' => $owner['url'],
1859                         'object' => self::getProfile($uid),
1860                         'published' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
1861                         'instrument' => self::getService(),
1862                         'to' => [$profile['followers']],
1863                         'cc' => []];
1864
1865                 $signed = LDSignature::sign($data, $owner);
1866
1867                 Logger::info('Deliver profile update for user ' . $uid . ' to ' . $inbox . ' via ActivityPub');
1868                 return HTTPSignature::transmit($signed, $inbox, $uid);
1869         }
1870
1871         /**
1872          * Transmits a given activity to a target
1873          *
1874          * @param string  $activity Type name
1875          * @param string  $target   Target profile
1876          * @param integer $uid      User ID
1877          * @return bool
1878          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1879          * @throws \ImagickException
1880          * @throws \Exception
1881          */
1882         public static function sendActivity($activity, $target, $uid, $id = '')
1883         {
1884                 $profile = APContact::getByURL($target);
1885                 if (empty($profile['inbox'])) {
1886                         Logger::warning('No inbox found for target', ['target' => $target, 'profile' => $profile]);
1887                         return;
1888                 }
1889
1890                 $owner = User::getOwnerDataById($uid);
1891
1892                 if (empty($id)) {
1893                         $id = DI::baseUrl() . '/activity/' . System::createGUID();
1894                 }
1895
1896                 $data = ['@context' => ActivityPub::CONTEXT,
1897                         'id' => $id,
1898                         'type' => $activity,
1899                         'actor' => $owner['url'],
1900                         'object' => $profile['url'],
1901                         'instrument' => self::getService(),
1902                         'to' => [$profile['url']]];
1903
1904                 Logger::info('Sending activity ' . $activity . ' to ' . $target . ' for user ' . $uid);
1905
1906                 $signed = LDSignature::sign($data, $owner);
1907                 return HTTPSignature::transmit($signed, $profile['inbox'], $uid);
1908         }
1909
1910         /**
1911          * Transmits a "follow object" activity to a target
1912          * This is a preparation for sending automated "follow" requests when receiving "Announce" messages
1913          *
1914          * @param string  $object Object URL
1915          * @param string  $target Target profile
1916          * @param integer $uid    User ID
1917          * @return bool
1918          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1919          * @throws \ImagickException
1920          * @throws \Exception
1921          */
1922         public static function sendFollowObject($object, $target, $uid = 0)
1923         {
1924                 $profile = APContact::getByURL($target);
1925                 if (empty($profile['inbox'])) {
1926                         Logger::warning('No inbox found for target', ['target' => $target, 'profile' => $profile]);
1927                         return;
1928                 }
1929
1930                 if (empty($uid)) {
1931                         // Fetch the list of administrators
1932                         $admin_mail = explode(',', str_replace(' ', '', DI::config()->get('config', 'admin_email')));
1933
1934                         // We need to use some user as a sender. It doesn't care who it will send. We will use an administrator account.
1935                         $condition = ['verified' => true, 'blocked' => false, 'account_removed' => false, 'account_expired' => false, 'email' => $admin_mail];
1936                         $first_user = DBA::selectFirst('user', ['uid'], $condition);
1937                         $uid = $first_user['uid'];
1938                 }
1939
1940                 $condition = ['verb' => Activity::FOLLOW, 'uid' => 0, 'parent-uri' => $object,
1941                         'author-id' => Contact::getPublicIdByUserId($uid)];
1942                 if (Post::exists($condition)) {
1943                         Logger::info('Follow for ' . $object . ' for user ' . $uid . ' does already exist.');
1944                         return false;
1945                 }
1946
1947                 $owner = User::getOwnerDataById($uid);
1948
1949                 $data = ['@context' => ActivityPub::CONTEXT,
1950                         'id' => DI::baseUrl() . '/activity/' . System::createGUID(),
1951                         'type' => 'Follow',
1952                         'actor' => $owner['url'],
1953                         'object' => $object,
1954                         'instrument' => self::getService(),
1955                         'to' => [$profile['url']]];
1956
1957                 Logger::info('Sending follow ' . $object . ' to ' . $target . ' for user ' . $uid);
1958
1959                 $signed = LDSignature::sign($data, $owner);
1960                 return HTTPSignature::transmit($signed, $profile['inbox'], $uid);
1961         }
1962
1963         /**
1964          * Transmit a message that the contact request had been accepted
1965          *
1966          * @param string  $target Target profile
1967          * @param         $id
1968          * @param integer $uid    User ID
1969          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1970          * @throws \ImagickException
1971          */
1972         public static function sendContactAccept($target, $id, $uid)
1973         {
1974                 $profile = APContact::getByURL($target);
1975                 if (empty($profile['inbox'])) {
1976                         Logger::warning('No inbox found for target', ['target' => $target, 'profile' => $profile]);
1977                         return;
1978                 }
1979
1980                 $owner = User::getOwnerDataById($uid);
1981                 $data = ['@context' => ActivityPub::CONTEXT,
1982                         'id' => DI::baseUrl() . '/activity/' . System::createGUID(),
1983                         'type' => 'Accept',
1984                         'actor' => $owner['url'],
1985                         'object' => [
1986                                 'id' => (string)$id,
1987                                 'type' => 'Follow',
1988                                 'actor' => $profile['url'],
1989                                 'object' => $owner['url']
1990                         ],
1991                         'instrument' => self::getService(),
1992                         'to' => [$profile['url']]];
1993
1994                 Logger::debug('Sending accept to ' . $target . ' for user ' . $uid . ' with id ' . $id);
1995
1996                 $signed = LDSignature::sign($data, $owner);
1997                 HTTPSignature::transmit($signed, $profile['inbox'], $uid);
1998         }
1999
2000         /**
2001          * Reject a contact request or terminates the contact relation
2002          *
2003          * @param string  $target Target profile
2004          * @param         $id
2005          * @param integer $uid    User ID
2006          * @return bool Operation success
2007          * @throws HTTPException\InternalServerErrorException
2008          * @throws \ImagickException
2009          */
2010         public static function sendContactReject($target, $id, $uid): bool
2011         {
2012                 $profile = APContact::getByURL($target);
2013                 if (empty($profile['inbox'])) {
2014                         Logger::warning('No inbox found for target', ['target' => $target, 'profile' => $profile]);
2015                         return false;
2016                 }
2017
2018                 $owner = User::getOwnerDataById($uid);
2019                 $data = ['@context' => ActivityPub::CONTEXT,
2020                         'id' => DI::baseUrl() . '/activity/' . System::createGUID(),
2021                         'type' => 'Reject',
2022                         'actor' => $owner['url'],
2023                         'object' => [
2024                                 'id' => (string)$id,
2025                                 'type' => 'Follow',
2026                                 'actor' => $profile['url'],
2027                                 'object' => $owner['url']
2028                         ],
2029                         'instrument' => self::getService(),
2030                         'to' => [$profile['url']]];
2031
2032                 Logger::debug('Sending reject to ' . $target . ' for user ' . $uid . ' with id ' . $id);
2033
2034                 $signed = LDSignature::sign($data, $owner);
2035                 return HTTPSignature::transmit($signed, $profile['inbox'], $uid);
2036         }
2037
2038         /**
2039          * Transmits a message that we don't want to follow this contact anymore
2040          *
2041          * @param string  $target Target profile
2042          * @param integer $uid    User ID
2043          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2044          * @throws \ImagickException
2045          * @throws \Exception
2046          * @return bool success
2047          */
2048         public static function sendContactUndo($target, $cid, $uid)
2049         {
2050                 $profile = APContact::getByURL($target);
2051                 if (empty($profile['inbox'])) {
2052                         Logger::warning('No inbox found for target', ['target' => $target, 'profile' => $profile]);
2053                         return false;
2054                 }
2055
2056                 $object_id = self::activityIDFromContact($cid);
2057                 if (empty($object_id)) {
2058                         return false;
2059                 }
2060
2061                 $id = DI::baseUrl() . '/activity/' . System::createGUID();
2062
2063                 $owner = User::getOwnerDataById($uid);
2064                 $data = ['@context' => ActivityPub::CONTEXT,
2065                         'id' => $id,
2066                         'type' => 'Undo',
2067                         'actor' => $owner['url'],
2068                         'object' => ['id' => $object_id, 'type' => 'Follow',
2069                                 'actor' => $owner['url'],
2070                                 'object' => $profile['url']],
2071                         'instrument' => self::getService(),
2072                         'to' => [$profile['url']]];
2073
2074                 Logger::info('Sending undo to ' . $target . ' for user ' . $uid . ' with id ' . $id);
2075
2076                 $signed = LDSignature::sign($data, $owner);
2077                 return HTTPSignature::transmit($signed, $profile['inbox'], $uid);
2078         }
2079
2080         private static function prependMentions($body, int $uriid, string $authorLink)
2081         {
2082                 $mentions = [];
2083
2084                 foreach (Tag::getByURIId($uriid, [Tag::IMPLICIT_MENTION]) as $tag) {
2085                         $profile = Contact::getByURL($tag['url'], false, ['addr', 'contact-type', 'nick']);
2086                         if (!empty($profile['addr'])
2087                                 && $profile['contact-type'] != Contact::TYPE_COMMUNITY
2088                                 && !strstr($body, $profile['addr'])
2089                                 && !strstr($body, $tag['url'])
2090                                 && $tag['url'] !== $authorLink
2091                         ) {
2092                                 $mentions[] = '@[url=' . $tag['url'] . ']' . $profile['nick'] . '[/url]';
2093                         }
2094                 }
2095
2096                 $mentions[] = $body;
2097
2098                 return implode(' ', $mentions);
2099         }
2100 }