]> git.mxchange.org Git - friendica.git/blob - src/Protocol/ActivityPub/Transmitter.php
Merge pull request #11255 from MrPetovan/task/11245-thread-completion-like
[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), 'uid' => $owner['uid'], 'blocked' => false]);
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_post "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_post = 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                                         $profile = APContact::getByURL($term['url'], false);
604                                         if (!empty($profile)) {
605                                                 if ($term['type'] == Tag::EXCLUSIVE_MENTION) {
606                                                         $exclusive = true;
607                                                         if (!empty($profile['followers']) && ($profile['type'] == 'Group')) {
608                                                                 $data['cc'][] = $profile['followers'];
609                                                         }
610                                                 }
611                                                 $data['to'][] = $profile['url'];
612                                         }
613                                 }
614                         }
615
616                         if (!$exclusive) {
617                                 foreach ($receiver_list as $receiver) {
618                                         $contact = DBA::selectFirst('contact', ['url', 'hidden', 'network', 'protocol', 'gsid'], ['id' => $receiver, 'network' => Protocol::FEDERATED]);
619                                         if (!DBA::isResult($contact) || !self::isAPContact($contact, $networks)) {
620                                                 continue;
621                                         }
622
623                                         if (!empty($profile = APContact::getByURL($contact['url'], false))) {
624                                                 if ($contact['hidden'] || $always_bcc) {
625                                                         $data['bcc'][] = $profile['url'];
626                                                 } else {
627                                                         $data['cc'][] = $profile['url'];
628                                                 }
629                                         }
630                                 }
631                         }
632                 }
633
634                 if (!empty($item['parent'])) {
635                         $parents = Post::select(['id', 'author-link', 'owner-link', 'gravity', 'uri'], ['parent' => $item['parent']]);
636                         while ($parent = Post::fetch($parents)) {
637                                 if ($parent['gravity'] == GRAVITY_PARENT) {
638                                         $profile = APContact::getByURL($parent['owner-link'], false);
639                                         if (!empty($profile)) {
640                                                 if ($item['gravity'] != GRAVITY_PARENT) {
641                                                         // Comments to forums are directed to the forum
642                                                         // But comments to forums aren't directed to the followers collection
643                                                         // This rule is only valid when the actor isn't the forum.
644                                                         // The forum needs to transmit their content to their followers.
645                                                         if (($profile['type'] == 'Group') && ($profile['url'] != ($actor_profile['url'] ?? ''))) {
646                                                                 $data['to'][] = $profile['url'];
647                                                         } else {
648                                                                 $data['cc'][] = $profile['url'];
649                                                                 if (($item['private'] != Item::PRIVATE) && !empty($actor_profile['followers'])) {
650                                                                         $data['cc'][] = $actor_profile['followers'];
651                                                                 }
652                                                         }
653                                                 } elseif (!$exclusive) {
654                                                         // Public thread parent post always are directed to the followers.
655                                                         // This mustn't be done by posts that are directed to forum servers via the exclusive mention.
656                                                         // But possibly in that case we could add the "followers" collection of the forum to the message.
657                                                         if (($item['private'] != Item::PRIVATE) && !$forum_post) {
658                                                                 $data['cc'][] = $actor_profile['followers'];
659                                                         }
660                                                 }
661                                         }
662                                 }
663
664                                 // Don't include data from future posts
665                                 if ($parent['id'] >= $last_id) {
666                                         continue;
667                                 }
668
669                                 $profile = APContact::getByURL($parent['author-link'], false);
670                                 if (!empty($profile)) {
671                                         if (($profile['type'] == 'Group') || ($parent['uri'] == $item['thr-parent'])) {
672                                                 $data['to'][] = $profile['url'];
673                                         } else {
674                                                 $data['cc'][] = $profile['url'];
675                                         }
676                                 }
677                         }
678                         DBA::close($parents);
679                 }
680
681                 $data['to'] = array_unique($data['to']);
682                 $data['cc'] = array_unique($data['cc']);
683                 $data['bcc'] = array_unique($data['bcc']);
684
685                 if (($key = array_search($item['author-link'], $data['to'])) !== false) {
686                         unset($data['to'][$key]);
687                 }
688
689                 if (($key = array_search($item['author-link'], $data['cc'])) !== false) {
690                         unset($data['cc'][$key]);
691                 }
692
693                 if (($key = array_search($item['author-link'], $data['bcc'])) !== false) {
694                         unset($data['bcc'][$key]);
695                 }
696
697                 foreach ($data['to'] as $to) {
698                         if (($key = array_search($to, $data['cc'])) !== false) {
699                                 unset($data['cc'][$key]);
700                         }
701
702                         if (($key = array_search($to, $data['bcc'])) !== false) {
703                                 unset($data['bcc'][$key]);
704                         }
705                 }
706
707                 foreach ($data['cc'] as $cc) {
708                         if (($key = array_search($cc, $data['bcc'])) !== false) {
709                                 unset($data['bcc'][$key]);
710                         }
711                 }
712
713                 $receivers = ['to' => array_values($data['to']), 'cc' => array_values($data['cc']), 'bcc' => array_values($data['bcc'])];
714
715                 if (!$blindcopy) {
716                         unset($receivers['bcc']);
717                 }
718
719                 return $receivers;
720         }
721
722         /**
723          * Check if an inbox is archived
724          *
725          * @param string $url Inbox url
726          *
727          * @return boolean "true" if inbox is archived
728          */
729         public static function archivedInbox($url)
730         {
731                 return DBA::exists('inbox-status', ['url' => $url, 'archive' => true]);
732         }
733
734         /**
735          * Check if a given contact should be delivered via AP
736          *
737          * @param array $contact
738          * @param array $networks
739          * @return bool
740          * @throws Exception
741          */
742         private static function isAPContact(array $contact, array $networks)
743         {
744                 if (in_array($contact['network'], $networks) || ($contact['protocol'] == Protocol::ACTIVITYPUB)) {
745                         return true;
746                 }
747
748                 return GServer::getProtocol($contact['gsid'] ?? 0) == Post\DeliveryData::ACTIVITYPUB;
749         }
750
751         /**
752          * Fetches a list of inboxes of followers of a given user
753          *
754          * @param integer $uid      User ID
755          * @param boolean $personal fetch personal inboxes
756          * @param boolean $all_ap   Retrieve all AP enabled inboxes
757          *
758          * @return array of follower inboxes
759          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
760          * @throws \ImagickException
761          */
762         public static function fetchTargetInboxesforUser($uid, $personal = false, bool $all_ap = false)
763         {
764                 $inboxes = [];
765
766                 $isforum = false;
767
768                 if (!empty($item['uid'])) {
769                         $profile = User::getOwnerDataById($item['uid']);
770                         if (!empty($profile)) {
771                                 $isforum = $profile['account-type'] == User::ACCOUNT_TYPE_COMMUNITY;
772                         }
773                 }
774
775                 if (DI::config()->get('debug', 'total_ap_delivery') || $all_ap) {
776                         // Will be activated in a later step
777                         $networks = Protocol::FEDERATED;
778                 } else {
779                         // For now only send to these contacts:
780                         $networks = [Protocol::ACTIVITYPUB, Protocol::OSTATUS];
781                 }
782
783                 $condition = ['uid' => $uid, 'archive' => false, 'pending' => false, 'blocked' => false, 'network' => Protocol::FEDERATED];
784
785                 if (!empty($uid)) {
786                         $condition['rel'] = [Contact::FOLLOWER, Contact::FRIEND];
787                 }
788
789                 $contacts = DBA::select('contact', ['id', 'url', 'network', 'protocol', 'gsid'], $condition);
790                 while ($contact = DBA::fetch($contacts)) {
791                         if (!self::isAPContact($contact, $networks)) {
792                                 continue;
793                         }
794
795                         if ($isforum && ($contact['network'] == Protocol::DFRN)) {
796                                 continue;
797                         }
798
799                         if (Network::isUrlBlocked($contact['url'])) {
800                                 continue;
801                         }
802
803                         $profile = APContact::getByURL($contact['url'], false);
804                         if (!empty($profile)) {
805                                 if (empty($profile['sharedinbox']) || $personal || Contact::isLocal($contact['url'])) {
806                                         $target = $profile['inbox'];
807                                 } else {
808                                         $target = $profile['sharedinbox'];
809                                 }
810                                 if (!self::archivedInbox($target)) {
811                                         $inboxes[$target][] = $contact['id'];
812                                 }
813                         }
814                 }
815                 DBA::close($contacts);
816
817                 return $inboxes;
818         }
819
820         /**
821          * Fetches an array of inboxes for the given item and user
822          *
823          * @param array   $item       Item array
824          * @param integer $uid        User ID
825          * @param boolean $personal   fetch personal inboxes
826          * @param integer $last_id    Last item id for adding receivers
827          * @param boolean $forum_post "true" means that we are sending content to a forum
828          * @return array with inboxes
829          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
830          * @throws \ImagickException
831          */
832         public static function fetchTargetInboxes($item, $uid, $personal = false, $last_id = 0, $forum_post = false)
833         {
834                 $permissions = self::createPermissionBlockForItem($item, true, $last_id, $forum_post);
835                 if (empty($permissions)) {
836                         return [];
837                 }
838
839                 $inboxes = [];
840
841                 if ($item['gravity'] == GRAVITY_ACTIVITY) {
842                         $item_profile = APContact::getByURL($item['author-link'], false);
843                 } else {
844                         $item_profile = APContact::getByURL($item['owner-link'], false);
845                 }
846
847                 if (empty($item_profile)) {
848                         return [];
849                 }
850
851                 $profile_uid = User::getIdForURL($item_profile['url']);
852
853                 foreach (['to', 'cc', 'bto', 'bcc'] as $element) {
854                         if (empty($permissions[$element])) {
855                                 continue;
856                         }
857
858                         $blindcopy = in_array($element, ['bto', 'bcc']);
859
860                         foreach ($permissions[$element] as $receiver) {
861                                 if (empty($receiver) || Network::isUrlBlocked($receiver)) {
862                                         continue;
863                                 }
864
865                                 if ($item_profile && ($receiver == $item_profile['followers']) && ($uid == $profile_uid)) {
866                                         $inboxes = array_merge($inboxes, self::fetchTargetInboxesforUser($uid, $personal, self::isAPPost($last_id)));
867                                 } else {
868                                         $profile = APContact::getByURL($receiver, false);
869                                         if (!empty($profile)) {
870                                                 $contact = Contact::getByURLForUser($receiver, $uid, false, ['id']);
871
872                                                 if (empty($profile['sharedinbox']) || $personal || $blindcopy || Contact::isLocal($receiver)) {
873                                                         $target = $profile['inbox'];
874                                                 } else {
875                                                         $target = $profile['sharedinbox'];
876                                                 }
877                                                 if (!self::archivedInbox($target)) {
878                                                         $inboxes[$target][] = $contact['id'] ?? 0;
879                                                 }
880                                         }
881                                 }
882                         }
883                 }
884
885                 return $inboxes;
886         }
887
888         /**
889          * Creates an array in the structure of the item table for a given mail id
890          *
891          * @param integer $mail_id
892          *
893          * @return array
894          * @throws \Exception
895          */
896         public static function ItemArrayFromMail($mail_id, $use_title = false)
897         {
898                 $mail = DBA::selectFirst('mail', [], ['id' => $mail_id]);
899                 if (!DBA::isResult($mail)) {
900                         return [];
901                 }
902
903                 $reply = DBA::selectFirst('mail', ['uri', 'uri-id', 'from-url'], ['parent-uri' => $mail['parent-uri'], 'reply' => false]);
904                 if (!DBA::isResult($reply)) {
905                         $reply = $mail;
906                 }
907
908                 // Making the post more compatible for Mastodon by:
909                 // - Making it a note and not an article (no title)
910                 // - Moving the title into the "summary" field that is used as a "content warning"
911
912                 if (!$use_title) {
913                         $mail['body']         = '[abstract]' . $mail['title'] . "[/abstract]\n" . $mail['body'];
914                         $mail['title']        = '';
915                 }
916
917                 $mail['author-link']      = $mail['owner-link'] = $mail['from-url'];
918                 $mail['owner-id']         = $mail['author-id'];
919                 $mail['allow_cid']        = '<'.$mail['contact-id'].'>';
920                 $mail['allow_gid']        = '';
921                 $mail['deny_cid']         = '';
922                 $mail['deny_gid']         = '';
923                 $mail['private']          = Item::PRIVATE;
924                 $mail['deleted']          = false;
925                 $mail['edited']           = $mail['created'];
926                 $mail['plink']            = DI::baseUrl() . '/message/' . $mail['id'];
927                 $mail['parent-uri']       = $reply['uri'];
928                 $mail['parent-uri-id']    = $reply['uri-id'];
929                 $mail['parent-author-id'] = Contact::getIdForURL($reply['from-url'], 0, false);
930                 $mail['gravity']          = ($mail['reply'] ? GRAVITY_COMMENT: GRAVITY_PARENT);
931                 $mail['event-type']       = '';
932                 $mail['language']         = '';
933                 $mail['parent']           = 0;
934
935                 return $mail;
936         }
937
938         /**
939          * Creates an activity array for a given mail id
940          *
941          * @param integer $mail_id
942          * @param boolean $object_mode Is the activity item is used inside another object?
943          *
944          * @return array of activity
945          * @throws \Exception
946          */
947         public static function createActivityFromMail($mail_id, $object_mode = false)
948         {
949                 $mail = self::ItemArrayFromMail($mail_id);
950                 if (empty($mail)) {
951                         return [];
952                 }
953                 $object = self::createNote($mail);
954
955                 if (!$object_mode) {
956                         $data = ['@context' => ActivityPub::CONTEXT];
957                 } else {
958                         $data = [];
959                 }
960
961                 $data['id'] = $mail['uri'] . '/Create';
962                 $data['type'] = 'Create';
963                 $data['actor'] = $mail['author-link'];
964                 $data['published'] = DateTimeFormat::utc($mail['created'] . '+00:00', DateTimeFormat::ATOM);
965                 $data['instrument'] = self::getService();
966                 $data = array_merge($data, self::createPermissionBlockForItem($mail, true));
967
968                 if (empty($data['to']) && !empty($data['cc'])) {
969                         $data['to'] = $data['cc'];
970                 }
971
972                 if (empty($data['to']) && !empty($data['bcc'])) {
973                         $data['to'] = $data['bcc'];
974                 }
975
976                 unset($data['cc']);
977                 unset($data['bcc']);
978
979                 $object['to'] = $data['to'];
980                 $object['tag'] = [['type' => 'Mention', 'href' => $object['to'][0], 'name' => '']];
981
982                 unset($object['cc']);
983                 unset($object['bcc']);
984
985                 $data['directMessage'] = true;
986
987                 $data['object'] = $object;
988
989                 $owner = User::getOwnerDataById($mail['uid']);
990
991                 if (!$object_mode && !empty($owner)) {
992                         return LDSignature::sign($data, $owner);
993                 } else {
994                         return $data;
995                 }
996         }
997
998         /**
999          * Returns the activity type of a given item
1000          *
1001          * @param array $item
1002          *
1003          * @return string with activity type
1004          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1005          * @throws \ImagickException
1006          */
1007         private static function getTypeOfItem($item)
1008         {
1009                 $reshared = false;
1010
1011                 // Only check for a reshare, if it is a real reshare and no quoted reshare
1012                 if (strpos($item['body'], "[share") === 0) {
1013                         $announce = self::getAnnounceArray($item);
1014                         $reshared = !empty($announce);
1015                 }
1016
1017                 if ($reshared) {
1018                         $type = 'Announce';
1019                 } elseif ($item['verb'] == Activity::POST) {
1020                         if ($item['created'] == $item['edited']) {
1021                                 $type = 'Create';
1022                         } else {
1023                                 $type = 'Update';
1024                         }
1025                 } elseif ($item['verb'] == Activity::LIKE) {
1026                         $type = 'Like';
1027                 } elseif ($item['verb'] == Activity::DISLIKE) {
1028                         $type = 'Dislike';
1029                 } elseif ($item['verb'] == Activity::ATTEND) {
1030                         $type = 'Accept';
1031                 } elseif ($item['verb'] == Activity::ATTENDNO) {
1032                         $type = 'Reject';
1033                 } elseif ($item['verb'] == Activity::ATTENDMAYBE) {
1034                         $type = 'TentativeAccept';
1035                 } elseif ($item['verb'] == Activity::FOLLOW) {
1036                         $type = 'Follow';
1037                 } elseif ($item['verb'] == Activity::TAG) {
1038                         $type = 'Add';
1039                 } elseif ($item['verb'] == Activity::ANNOUNCE) {
1040                         $type = 'Announce';
1041                 } else {
1042                         $type = '';
1043                 }
1044
1045                 return $type;
1046         }
1047
1048         /**
1049          * Creates the activity or fetches it from the cache
1050          *
1051          * @param integer $item_id
1052          * @param boolean $force Force new cache entry
1053          *
1054          * @return array with the activity
1055          * @throws \Exception
1056          */
1057         public static function createCachedActivityFromItem($item_id, $force = false)
1058         {
1059                 $cachekey = 'APDelivery:createActivity:' . $item_id;
1060
1061                 if (!$force) {
1062                         $data = DI::cache()->get($cachekey);
1063                         if (!is_null($data)) {
1064                                 return $data;
1065                         }
1066                 }
1067
1068                 $data = self::createActivityFromItem($item_id);
1069
1070                 DI::cache()->set($cachekey, $data, Duration::QUARTER_HOUR);
1071                 return $data;
1072         }
1073
1074         /**
1075          * Creates an activity array for a given item id
1076          *
1077          * @param integer $item_id
1078          * @param boolean $object_mode Is the activity item is used inside another object?
1079          *
1080          * @return false|array
1081          * @throws \Exception
1082          */
1083         public static function createActivityFromItem(int $item_id, bool $object_mode = false)
1084         {
1085                 Logger::info('Fetching activity', ['item' => $item_id]);
1086                 $item = Post::selectFirst(Item::DELIVER_FIELDLIST, ['id' => $item_id, 'parent-network' => Protocol::NATIVE_SUPPORT]);
1087                 if (!DBA::isResult($item)) {
1088                         return false;
1089                 }
1090
1091                 if (empty($item['uri-id'])) {
1092                         Logger::warning('Item without uri-id', ['item' => $item]);
1093                         return false;
1094                 }
1095
1096                 if (!$item['deleted']) {
1097                         $condition = ['item-uri' => $item['uri'], 'protocol' => Conversation::PARCEL_ACTIVITYPUB];
1098                         $conversation = DBA::selectFirst('conversation', ['source'], $condition);
1099                         if (!$item['origin'] && DBA::isResult($conversation)) {
1100                                 $data = json_decode($conversation['source'], true);
1101                                 if (!empty($data['type'])) {
1102                                         if (in_array($data['type'], ['Create', 'Update'])) {
1103                                                 if ($object_mode) {
1104                                                         unset($data['@context']);
1105                                                         unset($data['signature']);
1106                                                 }
1107                                                 Logger::info('Return stored conversation', ['item' => $item_id]);
1108                                                 return $data;
1109                                         } elseif (in_array('as:' . $data['type'], Receiver::CONTENT_TYPES)) {
1110                                                 if (!empty($data['@context'])) {
1111                                                         $context = $data['@context'];
1112                                                         unset($data['@context']);
1113                                                 }
1114                                                 unset($data['actor']);
1115                                                 $object = $data;
1116                                         }
1117                                 }
1118                         }
1119                 }
1120
1121                 $type = self::getTypeOfItem($item);
1122
1123                 if (!$object_mode) {
1124                         $data = ['@context' => $context ?? ActivityPub::CONTEXT];
1125
1126                         if ($item['deleted'] && ($item['gravity'] == GRAVITY_ACTIVITY)) {
1127                                 $type = 'Undo';
1128                         } elseif ($item['deleted']) {
1129                                 $type = 'Delete';
1130                         }
1131                 } else {
1132                         $data = [];
1133                 }
1134
1135                 if ($type == 'Delete') {
1136                         $data['id'] = Item::newURI($item['uid'], $item['guid']) . '/' . $type;;
1137                 } elseif (($item['gravity'] == GRAVITY_ACTIVITY) && ($type != 'Undo')) {
1138                         $data['id'] = $item['uri'];
1139                 } else {
1140                         $data['id'] = $item['uri'] . '/' . $type;
1141                 }
1142
1143                 $data['type'] = $type;
1144
1145                 if (($type != 'Announce') || ($item['gravity'] != GRAVITY_PARENT)) {
1146                         $data['actor'] = $item['author-link'];
1147                 } else {
1148                         $data['actor'] = $item['owner-link'];
1149                 }
1150
1151                 $data['published'] = DateTimeFormat::utc($item['created'] . '+00:00', DateTimeFormat::ATOM);
1152
1153                 $data['instrument'] = self::getService();
1154
1155                 $data = array_merge($data, self::createPermissionBlockForItem($item, false));
1156
1157                 if (in_array($data['type'], ['Create', 'Update', 'Delete'])) {
1158                         $data['object'] = $object ?? self::createNote($item);
1159                 } elseif ($data['type'] == 'Add') {
1160                         $data = self::createAddTag($item, $data);
1161                 } elseif ($data['type'] == 'Announce') {
1162                         if ($item['verb'] == ACTIVITY::ANNOUNCE) {
1163                                 $data['object'] = $item['thr-parent'];
1164                         } else {
1165                                 $data = self::createAnnounce($item, $data);
1166                         }
1167                 } elseif ($data['type'] == 'Follow') {
1168                         $data['object'] = $item['parent-uri'];
1169                 } elseif ($data['type'] == 'Undo') {
1170                         $data['object'] = self::createActivityFromItem($item_id, true);
1171                 } else {
1172                         $data['diaspora:guid'] = $item['guid'];
1173                         if (!empty($item['signed_text'])) {
1174                                 $data['diaspora:like'] = $item['signed_text'];
1175                         }
1176                         $data['object'] = $item['thr-parent'];
1177                 }
1178
1179                 if (!empty($item['contact-uid'])) {
1180                         $uid = $item['contact-uid'];
1181                 } else {
1182                         $uid = $item['uid'];
1183                 }
1184
1185                 $owner = User::getOwnerDataById($uid);
1186
1187                 Logger::info('Fetched activity', ['item' => $item_id, 'uid' => $uid]);
1188
1189                 // We don't sign if we aren't the actor. This is important for relaying content especially for forums
1190                 if (!$object_mode && !empty($owner) && ($data['actor'] == $owner['url'])) {
1191                         return LDSignature::sign($data, $owner);
1192                 } else {
1193                         return $data;
1194                 }
1195
1196                 /// @todo Create "conversation" entry
1197         }
1198
1199         /**
1200          * Creates a location entry for a given item array
1201          *
1202          * @param array $item
1203          *
1204          * @return array with location array
1205          */
1206         private static function createLocation($item)
1207         {
1208                 $location = ['type' => 'Place'];
1209
1210                 if (!empty($item['location'])) {
1211                         $location['name'] = $item['location'];
1212                 }
1213
1214                 $coord = [];
1215
1216                 if (empty($item['coord'])) {
1217                         $coord = Map::getCoordinates($item['location']);
1218                 } else {
1219                         $coords = explode(' ', $item['coord']);
1220                         if (count($coords) == 2) {
1221                                 $coord = ['lat' => $coords[0], 'lon' => $coords[1]];
1222                         }
1223                 }
1224
1225                 if (!empty($coord['lat']) && !empty($coord['lon'])) {
1226                         $location['latitude'] = $coord['lat'];
1227                         $location['longitude'] = $coord['lon'];
1228                 }
1229
1230                 return $location;
1231         }
1232
1233         /**
1234          * Returns a tag array for a given item array
1235          *
1236          * @param array $item
1237          *
1238          * @return array of tags
1239          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1240          */
1241         private static function createTagList($item)
1242         {
1243                 $tags = [];
1244
1245                 $terms = Tag::getByURIId($item['uri-id'], [Tag::HASHTAG, Tag::MENTION, Tag::IMPLICIT_MENTION, Tag::EXCLUSIVE_MENTION]);
1246                 foreach ($terms as $term) {
1247                         if ($term['type'] == Tag::HASHTAG) {
1248                                 $url = DI::baseUrl() . '/search?tag=' . urlencode($term['name']);
1249                                 $tags[] = ['type' => 'Hashtag', 'href' => $url, 'name' => '#' . $term['name']];
1250                         } else {
1251                                 $contact = Contact::getByURL($term['url'], false, ['addr']);
1252                                 if (empty($contact)) {
1253                                         continue;
1254                                 }
1255                                 if (!empty($contact['addr'])) {
1256                                         $mention = '@' . $contact['addr'];
1257                                 } else {
1258                                         $mention = '@' . $term['url'];
1259                                 }
1260
1261                                 $tags[] = ['type' => 'Mention', 'href' => $term['url'], 'name' => $mention];
1262                         }
1263                 }
1264
1265                 $announce = self::getAnnounceArray($item);
1266                 // Mention the original author upon commented reshares
1267                 if (!empty($announce['comment'])) {
1268                         $tags[] = ['type' => 'Mention', 'href' => $announce['actor']['url'], 'name' => '@' . $announce['actor']['addr']];
1269                 }
1270
1271                 return $tags;
1272         }
1273
1274         /**
1275          * Adds attachment data to the JSON document
1276          *
1277          * @param array  $item Data of the item that is to be posted
1278          * @param string $type Object type
1279          *
1280          * @return array with attachment data
1281          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1282          */
1283         private static function createAttachmentList($item, $type)
1284         {
1285                 $attachments = [];
1286
1287                 $uriids = [$item['uri-id']];
1288                 $shared = BBCode::fetchShareAttributes($item['body']);
1289                 if (!empty($shared['guid'])) {
1290                         $shared_item = Post::selectFirst(['uri-id'], ['guid' => $shared['guid']]);
1291                         if (!empty($shared_item['uri-id'])) {
1292                                 $uriids[] = $shared_item['uri-id'];
1293                         }
1294                 }
1295
1296                 $urls = [];
1297                 foreach ($uriids as $uriid) {
1298                         foreach (Post\Media::getByURIId($uriid, [Post\Media::AUDIO, Post\Media::IMAGE, Post\Media::VIDEO, Post\Media::DOCUMENT, Post\Media::TORRENT]) as $attachment) {
1299                                 if (in_array($attachment['url'], $urls)) {
1300                                         continue;
1301                                 }
1302                                 $urls[] = $attachment['url'];
1303
1304                                 $attach = ['type' => 'Document',
1305                                         'mediaType' => $attachment['mimetype'],
1306                                         'url' => $attachment['url'],
1307                                         'name' => $attachment['description']];
1308
1309                                 if (!empty($attachment['height'])) {
1310                                         $attach['height'] = $attachment['height'];
1311                                 }
1312
1313                                 if (!empty($attachment['width'])) {
1314                                         $attach['width'] = $attachment['width'];
1315                                 }
1316
1317                                 if (!empty($attachment['preview'])) {
1318                                         $attach['image'] = $attachment['preview'];
1319                                 }
1320
1321                                 $attachments[] = $attach;
1322                         }
1323                 }
1324
1325                 return $attachments;
1326         }
1327
1328         /**
1329          * Callback function to replace a Friendica style mention in a mention for a summary
1330          *
1331          * @param array $match Matching values for the callback
1332          * @return string Replaced mention
1333          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1334          */
1335         private static function mentionAddrCallback($match)
1336         {
1337                 if (empty($match[1])) {
1338                         return '';
1339                 }
1340
1341                 $data = Contact::getByURL($match[1], false, ['addr']);
1342                 if (empty($data['addr'])) {
1343                         return $match[0];
1344                 }
1345
1346                 return '@' . $data['addr'];
1347         }
1348
1349         /**
1350          * Remove image elements since they are added as attachment
1351          *
1352          * @param string $body
1353          *
1354          * @return string with removed images
1355          */
1356         private static function removePictures($body)
1357         {
1358                 // Simplify image codes
1359                 $body = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '[img]$3[/img]', $body);
1360                 $body = preg_replace("/\[img\=(.*?)\](.*?)\[\/img\]/ism", '[img]$1[/img]', $body);
1361
1362                 // Now remove local links
1363                 $body = preg_replace_callback(
1364                         '/\[url=([^\[\]]*)\]\[img\](.*)\[\/img\]\[\/url\]/Usi',
1365                         function ($match) {
1366                                 // We remove the link when it is a link to a local photo page
1367                                 if (Photo::isLocalPage($match[1])) {
1368                                         return '';
1369                                 }
1370                                 // otherwise we just return the link
1371                                 return '[url]' . $match[1] . '[/url]';
1372                         },
1373                         $body
1374                 );
1375
1376                 // Remove all pictures
1377                 $body = preg_replace("/\[img\]([^\[\]]*)\[\/img\]/Usi", '', $body);
1378
1379                 return $body;
1380         }
1381
1382         /**
1383          * Fetches the "context" value for a givem item array from the "conversation" table
1384          *
1385          * @param array $item
1386          *
1387          * @return string with context url
1388          * @throws \Exception
1389          */
1390         private static function fetchContextURLForItem($item)
1391         {
1392                 $conversation = DBA::selectFirst('conversation', ['conversation-href', 'conversation-uri'], ['item-uri' => $item['parent-uri']]);
1393                 if (DBA::isResult($conversation) && !empty($conversation['conversation-href'])) {
1394                         $context_uri = $conversation['conversation-href'];
1395                 } elseif (DBA::isResult($conversation) && !empty($conversation['conversation-uri'])) {
1396                         $context_uri = $conversation['conversation-uri'];
1397                 } else {
1398                         $context_uri = $item['parent-uri'] . '#context';
1399                 }
1400                 return $context_uri;
1401         }
1402
1403         /**
1404          * Returns if the post contains sensitive content ("nsfw")
1405          *
1406          * @param integer $uri_id
1407          *
1408          * @return boolean
1409          * @throws \Exception
1410          */
1411         private static function isSensitive($uri_id)
1412         {
1413                 return DBA::exists('tag-view', ['uri-id' => $uri_id, 'name' => 'nsfw']);
1414         }
1415
1416         /**
1417          * Creates event data
1418          *
1419          * @param array $item
1420          *
1421          * @return array with the event data
1422          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1423          */
1424         private static function createEvent($item)
1425         {
1426                 $event = [];
1427                 $event['name'] = $item['event-summary'];
1428                 $event['content'] = BBCode::convertForUriId($item['uri-id'], $item['event-desc'], BBCode::ACTIVITYPUB);
1429                 $event['startTime'] = DateTimeFormat::utc($item['event-start'], 'c');
1430
1431                 if (!$item['event-nofinish']) {
1432                         $event['endTime'] = DateTimeFormat::utc($item['event-finish'], 'c');
1433                 }
1434
1435                 if (!empty($item['event-location'])) {
1436                         $item['location'] = $item['event-location'];
1437                         $event['location'] = self::createLocation($item);
1438                 }
1439
1440                 // 2021.12: Backward compatibility value, all the events now "adjust" to the viewer timezone
1441                 $event['dfrn:adjust'] = true;
1442
1443                 return $event;
1444         }
1445
1446         /**
1447          * Creates a note/article object array
1448          *
1449          * @param array $item
1450          *
1451          * @return array with the object data
1452          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1453          * @throws \ImagickException
1454          */
1455         public static function createNote($item)
1456         {
1457                 if (empty($item)) {
1458                         return [];
1459                 }
1460
1461                 if ($item['event-type'] == 'event') {
1462                         $type = 'Event';
1463                 } elseif (!empty($item['title'])) {
1464                         $type = 'Article';
1465                 } else {
1466                         $type = 'Note';
1467                 }
1468
1469                 if ($item['deleted']) {
1470                         $type = 'Tombstone';
1471                 }
1472
1473                 $data = [];
1474                 $data['id'] = $item['uri'];
1475                 $data['type'] = $type;
1476
1477                 if ($item['deleted']) {
1478                         return $data;
1479                 }
1480
1481                 $data['summary'] = BBCode::toPlaintext(BBCode::getAbstract($item['body'], Protocol::ACTIVITYPUB));
1482
1483                 if ($item['uri'] != $item['thr-parent']) {
1484                         $data['inReplyTo'] = $item['thr-parent'];
1485                 } else {
1486                         $data['inReplyTo'] = null;
1487                 }
1488
1489                 $data['diaspora:guid'] = $item['guid'];
1490                 $data['published'] = DateTimeFormat::utc($item['created'] . '+00:00', DateTimeFormat::ATOM);
1491
1492                 if ($item['created'] != $item['edited']) {
1493                         $data['updated'] = DateTimeFormat::utc($item['edited'] . '+00:00', DateTimeFormat::ATOM);
1494                 }
1495
1496                 $data['url'] = $item['plink'];
1497                 $data['attributedTo'] = $item['author-link'];
1498                 $data['sensitive'] = self::isSensitive($item['uri-id']);
1499                 $data['context'] = self::fetchContextURLForItem($item);
1500
1501                 if (!empty($item['title'])) {
1502                         $data['name'] = BBCode::toPlaintext($item['title'], false);
1503                 }
1504
1505                 $permission_block = self::createPermissionBlockForItem($item, false);
1506
1507                 $body = $item['body'];
1508
1509                 if ($type == 'Note') {
1510                         $body = $item['raw-body'] ?? self::removePictures($body);
1511                 }
1512
1513                 /**
1514                  * @todo Improve the automated summary
1515                  * This part is currently deactivated. The automated summary seems to be more
1516                  * confusing than helping. But possibly we will find a better way.
1517                  * So the code is left here for now as a reminder
1518                  *
1519                  * } elseif (($type == 'Article') && empty($data['summary'])) {
1520                  *              $regexp = "/[@!]\[url\=([^\[\]]*)\].*?\[\/url\]/ism";
1521                  *              $summary = preg_replace_callback($regexp, ['self', 'mentionAddrCallback'], $body);
1522                  *              $data['summary'] = BBCode::toPlaintext(Plaintext::shorten(self::removePictures($summary), 1000));
1523                  * }
1524                  */
1525
1526                 if (empty($item['uid']) || !Feature::isEnabled($item['uid'], 'explicit_mentions')) {
1527                         $body = self::prependMentions($body, $item['uri-id'], $item['author-link']);
1528                 }
1529
1530                 if ($type == 'Event') {
1531                         $data = array_merge($data, self::createEvent($item));
1532                 } else {
1533                         $body = BBCode::setMentionsToNicknames($body);
1534
1535                         $data['content'] = BBCode::convertForUriId($item['uri-id'], $body, BBCode::ACTIVITYPUB);
1536                 }
1537
1538                 // The regular "content" field does contain a minimized HTML. This is done since systems like
1539                 // Mastodon has got problems with - for example - embedded pictures.
1540                 // The contentMap does contain the unmodified HTML.
1541                 $language = self::getLanguage($item);
1542                 if (!empty($language)) {
1543                         $richbody = BBCode::setMentionsToNicknames($item['body'] ?? '');
1544                         $richbody = BBCode::removeAttachment($richbody);
1545
1546                         $data['contentMap'][$language] = BBCode::convertForUriId($item['uri-id'], $richbody, BBCode::EXTERNAL);
1547                 }
1548
1549                 $data['source'] = ['content' => $item['body'], 'mediaType' => "text/bbcode"];
1550
1551                 if (!empty($item['signed_text']) && ($item['uri'] != $item['thr-parent'])) {
1552                         $data['diaspora:comment'] = $item['signed_text'];
1553                 }
1554
1555                 $data['attachment'] = self::createAttachmentList($item, $type);
1556                 $data['tag'] = self::createTagList($item);
1557
1558                 if (empty($data['location']) && (!empty($item['coord']) || !empty($item['location']))) {
1559                         $data['location'] = self::createLocation($item);
1560                 }
1561
1562                 if (!empty($item['app'])) {
1563                         $data['generator'] = ['type' => 'Application', 'name' => $item['app']];
1564                 }
1565
1566                 $data = array_merge($data, $permission_block);
1567
1568                 return $data;
1569         }
1570
1571         /**
1572          * Fetches the language from the post, the user or the system.
1573          *
1574          * @param array $item
1575          *
1576          * @return string language string
1577          */
1578         private static function getLanguage(array $item)
1579         {
1580                 // Try to fetch the language from the post itself
1581                 if (!empty($item['language'])) {
1582                         $languages = array_keys(json_decode($item['language'], true));
1583                         if (!empty($languages[0])) {
1584                                 return $languages[0];
1585                         }
1586                 }
1587
1588                 // Otherwise use the user's language
1589                 if (!empty($item['uid'])) {
1590                         $user = DBA::selectFirst('user', ['language'], ['uid' => $item['uid']]);
1591                         if (!empty($user['language'])) {
1592                                 return $user['language'];
1593                         }
1594                 }
1595
1596                 // And finally just use the system language
1597                 return DI::config()->get('system', 'language');
1598         }
1599
1600         /**
1601          * Creates an an "add tag" entry
1602          *
1603          * @param array $item
1604          * @param array $data activity data
1605          *
1606          * @return array with activity data for adding tags
1607          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1608          * @throws \ImagickException
1609          */
1610         private static function createAddTag($item, $data)
1611         {
1612                 $object = XML::parseString($item['object']);
1613                 $target = XML::parseString($item["target"]);
1614
1615                 $data['diaspora:guid'] = $item['guid'];
1616                 $data['actor'] = $item['author-link'];
1617                 $data['target'] = (string)$target->id;
1618                 $data['summary'] = BBCode::toPlaintext($item['body']);
1619                 $data['object'] = ['id' => (string)$object->id, 'type' => 'tag', 'name' => (string)$object->title, 'content' => (string)$object->content];
1620
1621                 return $data;
1622         }
1623
1624         /**
1625          * Creates an announce object entry
1626          *
1627          * @param array $item
1628          * @param array $data activity data
1629          *
1630          * @return array with activity data
1631          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1632          * @throws \ImagickException
1633          */
1634         private static function createAnnounce($item, $data)
1635         {
1636                 $orig_body = $item['body'];
1637                 $announce = self::getAnnounceArray($item);
1638                 if (empty($announce)) {
1639                         $data['type'] = 'Create';
1640                         $data['object'] = self::createNote($item);
1641                         return $data;
1642                 }
1643
1644                 if (empty($announce['comment'])) {
1645                         // Pure announce, without a quote
1646                         $data['type'] = 'Announce';
1647                         $data['object'] = $announce['object']['uri'];
1648                         return $data;
1649                 }
1650
1651                 // Quote
1652                 $data['type'] = 'Create';
1653                 $item['body'] = $announce['comment'] . "\n" . $announce['object']['plink'];
1654                 $data['object'] = self::createNote($item);
1655
1656                 /// @todo Finally descide how to implement this in AP. This is a possible way:
1657                 $data['object']['attachment'][] = self::createNote($announce['object']);
1658
1659                 $data['object']['source']['content'] = $orig_body;
1660                 return $data;
1661         }
1662
1663         /**
1664          * Return announce related data if the item is an annunce
1665          *
1666          * @param array $item
1667          *
1668          * @return array
1669          */
1670         public static function getAnnounceArray($item)
1671         {
1672                 $reshared = Item::getShareArray($item);
1673                 if (empty($reshared['guid'])) {
1674                         return [];
1675                 }
1676
1677                 $reshared_item = Post::selectFirst(Item::DELIVER_FIELDLIST, ['guid' => $reshared['guid']]);
1678                 if (!DBA::isResult($reshared_item)) {
1679                         return [];
1680                 }
1681
1682                 if (!in_array($reshared_item['network'], [Protocol::ACTIVITYPUB, Protocol::DFRN])) {
1683                         return [];
1684                 }
1685
1686                 $profile = APContact::getByURL($reshared_item['author-link'], false);
1687                 if (empty($profile)) {
1688                         return [];
1689                 }
1690
1691                 return ['object' => $reshared_item, 'actor' => $profile, 'comment' => $reshared['comment']];
1692         }
1693
1694         /**
1695          * Checks if the provided item array is an announce
1696          *
1697          * @param array $item
1698          *
1699          * @return boolean
1700          */
1701         public static function isAnnounce($item)
1702         {
1703                 if (!empty($item['verb']) && ($item['verb'] == Activity::ANNOUNCE)) {
1704                         return true;
1705                 }
1706
1707                 $announce = self::getAnnounceArray($item);
1708                 if (empty($announce)) {
1709                         return false;
1710                 }
1711
1712                 return empty($announce['comment']);
1713         }
1714
1715         /**
1716          * Creates an activity id for a given contact id
1717          *
1718          * @param integer $cid Contact ID of target
1719          *
1720          * @return bool|string activity id
1721          */
1722         public static function activityIDFromContact($cid)
1723         {
1724                 $contact = DBA::selectFirst('contact', ['uid', 'id', 'created'], ['id' => $cid]);
1725                 if (!DBA::isResult($contact)) {
1726                         return false;
1727                 }
1728
1729                 $hash = hash('ripemd128', $contact['uid'].'-'.$contact['id'].'-'.$contact['created']);
1730                 $uuid = substr($hash, 0, 8). '-' . substr($hash, 8, 4) . '-' . substr($hash, 12, 4) . '-' . substr($hash, 16, 4) . '-' . substr($hash, 20, 12);
1731                 return DI::baseUrl() . '/activity/' . $uuid;
1732         }
1733
1734         /**
1735          * Transmits a contact suggestion to a given inbox
1736          *
1737          * @param integer $uid           User ID
1738          * @param string  $inbox         Target inbox
1739          * @param integer $suggestion_id Suggestion ID
1740          *
1741          * @return boolean was the transmission successful?
1742          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1743          */
1744         public static function sendContactSuggestion($uid, $inbox, $suggestion_id)
1745         {
1746                 $owner = User::getOwnerDataById($uid);
1747
1748                 $suggestion = DI::fsuggest()->selectOneById($suggestion_id);
1749
1750                 $data = ['@context' => ActivityPub::CONTEXT,
1751                         'id' => DI::baseUrl() . '/activity/' . System::createGUID(),
1752                         'type' => 'Announce',
1753                         'actor' => $owner['url'],
1754                         'object' => $suggestion->url,
1755                         'content' => $suggestion->note,
1756                         'instrument' => self::getService(),
1757                         'to' => [ActivityPub::PUBLIC_COLLECTION],
1758                         'cc' => []];
1759
1760                 $signed = LDSignature::sign($data, $owner);
1761
1762                 Logger::info('Deliver profile deletion for user ' . $uid . ' to ' . $inbox . ' via ActivityPub');
1763                 return HTTPSignature::transmit($signed, $inbox, $uid);
1764         }
1765
1766         /**
1767          * Transmits a profile relocation to a given inbox
1768          *
1769          * @param integer $uid   User ID
1770          * @param string  $inbox Target inbox
1771          *
1772          * @return boolean was the transmission successful?
1773          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1774          */
1775         public static function sendProfileRelocation($uid, $inbox)
1776         {
1777                 $owner = User::getOwnerDataById($uid);
1778
1779                 $data = ['@context' => ActivityPub::CONTEXT,
1780                         'id' => DI::baseUrl() . '/activity/' . System::createGUID(),
1781                         'type' => 'dfrn:relocate',
1782                         'actor' => $owner['url'],
1783                         'object' => $owner['url'],
1784                         'published' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
1785                         'instrument' => self::getService(),
1786                         'to' => [ActivityPub::PUBLIC_COLLECTION],
1787                         'cc' => []];
1788
1789                 $signed = LDSignature::sign($data, $owner);
1790
1791                 Logger::info('Deliver profile relocation for user ' . $uid . ' to ' . $inbox . ' via ActivityPub');
1792                 return HTTPSignature::transmit($signed, $inbox, $uid);
1793         }
1794
1795         /**
1796          * Transmits a profile deletion to a given inbox
1797          *
1798          * @param integer $uid   User ID
1799          * @param string  $inbox Target inbox
1800          *
1801          * @return boolean was the transmission successful?
1802          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1803          */
1804         public static function sendProfileDeletion($uid, $inbox)
1805         {
1806                 $owner = User::getOwnerDataById($uid);
1807
1808                 if (empty($owner)) {
1809                         Logger::error('No owner data found, the deletion message cannot be processed.', ['user' => $uid]);
1810                         return false;
1811                 }
1812
1813                 if (empty($owner['uprvkey'])) {
1814                         Logger::error('No private key for owner found, the deletion message cannot be processed.', ['user' => $uid]);
1815                         return false;
1816                 }
1817
1818                 $data = ['@context' => ActivityPub::CONTEXT,
1819                         'id' => DI::baseUrl() . '/activity/' . System::createGUID(),
1820                         'type' => 'Delete',
1821                         'actor' => $owner['url'],
1822                         'object' => $owner['url'],
1823                         'published' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
1824                         'instrument' => self::getService(),
1825                         'to' => [ActivityPub::PUBLIC_COLLECTION],
1826                         'cc' => []];
1827
1828                 $signed = LDSignature::sign($data, $owner);
1829
1830                 Logger::info('Deliver profile deletion for user ' . $uid . ' to ' . $inbox . ' via ActivityPub');
1831                 return HTTPSignature::transmit($signed, $inbox, $uid);
1832         }
1833
1834         /**
1835          * Transmits a profile change to a given inbox
1836          *
1837          * @param integer $uid   User ID
1838          * @param string  $inbox Target inbox
1839          *
1840          * @return boolean was the transmission successful?
1841          * @throws HTTPException\InternalServerErrorException
1842          * @throws HTTPException\NotFoundException
1843          * @throws \ImagickException
1844          */
1845         public static function sendProfileUpdate(int $uid, string $inbox): bool
1846         {
1847                 $owner = User::getOwnerDataById($uid);
1848                 $profile = APContact::getByURL($owner['url']);
1849
1850                 $data = ['@context' => ActivityPub::CONTEXT,
1851                         'id' => DI::baseUrl() . '/activity/' . System::createGUID(),
1852                         'type' => 'Update',
1853                         'actor' => $owner['url'],
1854                         'object' => self::getProfile($uid),
1855                         'published' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
1856                         'instrument' => self::getService(),
1857                         'to' => [$profile['followers']],
1858                         'cc' => []];
1859
1860                 $signed = LDSignature::sign($data, $owner);
1861
1862                 Logger::info('Deliver profile update for user ' . $uid . ' to ' . $inbox . ' via ActivityPub');
1863                 return HTTPSignature::transmit($signed, $inbox, $uid);
1864         }
1865
1866         /**
1867          * Transmits a given activity to a target
1868          *
1869          * @param string  $activity Type name
1870          * @param string  $target   Target profile
1871          * @param integer $uid      User ID
1872          * @return bool
1873          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1874          * @throws \ImagickException
1875          * @throws \Exception
1876          */
1877         public static function sendActivity($activity, $target, $uid, $id = '')
1878         {
1879                 $profile = APContact::getByURL($target);
1880                 if (empty($profile['inbox'])) {
1881                         Logger::warning('No inbox found for target', ['target' => $target, 'profile' => $profile]);
1882                         return;
1883                 }
1884
1885                 $owner = User::getOwnerDataById($uid);
1886
1887                 if (empty($id)) {
1888                         $id = DI::baseUrl() . '/activity/' . System::createGUID();
1889                 }
1890
1891                 $data = ['@context' => ActivityPub::CONTEXT,
1892                         'id' => $id,
1893                         'type' => $activity,
1894                         'actor' => $owner['url'],
1895                         'object' => $profile['url'],
1896                         'instrument' => self::getService(),
1897                         'to' => [$profile['url']]];
1898
1899                 Logger::info('Sending activity ' . $activity . ' to ' . $target . ' for user ' . $uid);
1900
1901                 $signed = LDSignature::sign($data, $owner);
1902                 return HTTPSignature::transmit($signed, $profile['inbox'], $uid);
1903         }
1904
1905         /**
1906          * Transmits a "follow object" activity to a target
1907          * This is a preparation for sending automated "follow" requests when receiving "Announce" messages
1908          *
1909          * @param string  $object Object URL
1910          * @param string  $target Target profile
1911          * @param integer $uid    User ID
1912          * @return bool
1913          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1914          * @throws \ImagickException
1915          * @throws \Exception
1916          */
1917         public static function sendFollowObject($object, $target, $uid = 0)
1918         {
1919                 $profile = APContact::getByURL($target);
1920                 if (empty($profile['inbox'])) {
1921                         Logger::warning('No inbox found for target', ['target' => $target, 'profile' => $profile]);
1922                         return;
1923                 }
1924
1925                 if (empty($uid)) {
1926                         // Fetch the list of administrators
1927                         $admin_mail = explode(',', str_replace(' ', '', DI::config()->get('config', 'admin_email')));
1928
1929                         // We need to use some user as a sender. It doesn't care who it will send. We will use an administrator account.
1930                         $condition = ['verified' => true, 'blocked' => false, 'account_removed' => false, 'account_expired' => false, 'email' => $admin_mail];
1931                         $first_user = DBA::selectFirst('user', ['uid'], $condition);
1932                         $uid = $first_user['uid'];
1933                 }
1934
1935                 $condition = ['verb' => Activity::FOLLOW, 'uid' => 0, 'parent-uri' => $object,
1936                         'author-id' => Contact::getPublicIdByUserId($uid)];
1937                 if (Post::exists($condition)) {
1938                         Logger::info('Follow for ' . $object . ' for user ' . $uid . ' does already exist.');
1939                         return false;
1940                 }
1941
1942                 $owner = User::getOwnerDataById($uid);
1943
1944                 $data = ['@context' => ActivityPub::CONTEXT,
1945                         'id' => DI::baseUrl() . '/activity/' . System::createGUID(),
1946                         'type' => 'Follow',
1947                         'actor' => $owner['url'],
1948                         'object' => $object,
1949                         'instrument' => self::getService(),
1950                         'to' => [$profile['url']]];
1951
1952                 Logger::info('Sending follow ' . $object . ' to ' . $target . ' for user ' . $uid);
1953
1954                 $signed = LDSignature::sign($data, $owner);
1955                 return HTTPSignature::transmit($signed, $profile['inbox'], $uid);
1956         }
1957
1958         /**
1959          * Transmit a message that the contact request had been accepted
1960          *
1961          * @param string  $target Target profile
1962          * @param         $id
1963          * @param integer $uid    User ID
1964          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1965          * @throws \ImagickException
1966          */
1967         public static function sendContactAccept($target, $id, $uid)
1968         {
1969                 $profile = APContact::getByURL($target);
1970                 if (empty($profile['inbox'])) {
1971                         Logger::warning('No inbox found for target', ['target' => $target, 'profile' => $profile]);
1972                         return;
1973                 }
1974
1975                 $owner = User::getOwnerDataById($uid);
1976                 $data = ['@context' => ActivityPub::CONTEXT,
1977                         'id' => DI::baseUrl() . '/activity/' . System::createGUID(),
1978                         'type' => 'Accept',
1979                         'actor' => $owner['url'],
1980                         'object' => [
1981                                 'id' => (string)$id,
1982                                 'type' => 'Follow',
1983                                 'actor' => $profile['url'],
1984                                 'object' => $owner['url']
1985                         ],
1986                         'instrument' => self::getService(),
1987                         'to' => [$profile['url']]];
1988
1989                 Logger::debug('Sending accept to ' . $target . ' for user ' . $uid . ' with id ' . $id);
1990
1991                 $signed = LDSignature::sign($data, $owner);
1992                 HTTPSignature::transmit($signed, $profile['inbox'], $uid);
1993         }
1994
1995         /**
1996          * Reject a contact request or terminates the contact relation
1997          *
1998          * @param string  $target Target profile
1999          * @param         $id
2000          * @param integer $uid    User ID
2001          * @return bool Operation success
2002          * @throws HTTPException\InternalServerErrorException
2003          * @throws \ImagickException
2004          */
2005         public static function sendContactReject($target, $id, $uid): bool
2006         {
2007                 $profile = APContact::getByURL($target);
2008                 if (empty($profile['inbox'])) {
2009                         Logger::warning('No inbox found for target', ['target' => $target, 'profile' => $profile]);
2010                         return false;
2011                 }
2012
2013                 $owner = User::getOwnerDataById($uid);
2014                 $data = ['@context' => ActivityPub::CONTEXT,
2015                         'id' => DI::baseUrl() . '/activity/' . System::createGUID(),
2016                         'type' => 'Reject',
2017                         'actor' => $owner['url'],
2018                         'object' => [
2019                                 'id' => (string)$id,
2020                                 'type' => 'Follow',
2021                                 'actor' => $profile['url'],
2022                                 'object' => $owner['url']
2023                         ],
2024                         'instrument' => self::getService(),
2025                         'to' => [$profile['url']]];
2026
2027                 Logger::debug('Sending reject to ' . $target . ' for user ' . $uid . ' with id ' . $id);
2028
2029                 $signed = LDSignature::sign($data, $owner);
2030                 return HTTPSignature::transmit($signed, $profile['inbox'], $uid);
2031         }
2032
2033         /**
2034          * Transmits a message that we don't want to follow this contact anymore
2035          *
2036          * @param string  $target Target profile
2037          * @param integer $uid    User ID
2038          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2039          * @throws \ImagickException
2040          * @throws \Exception
2041          * @return bool success
2042          */
2043         public static function sendContactUndo($target, $cid, $uid)
2044         {
2045                 $profile = APContact::getByURL($target);
2046                 if (empty($profile['inbox'])) {
2047                         Logger::warning('No inbox found for target', ['target' => $target, 'profile' => $profile]);
2048                         return false;
2049                 }
2050
2051                 $object_id = self::activityIDFromContact($cid);
2052                 if (empty($object_id)) {
2053                         return false;
2054                 }
2055
2056                 $id = DI::baseUrl() . '/activity/' . System::createGUID();
2057
2058                 $owner = User::getOwnerDataById($uid);
2059                 $data = ['@context' => ActivityPub::CONTEXT,
2060                         'id' => $id,
2061                         'type' => 'Undo',
2062                         'actor' => $owner['url'],
2063                         'object' => ['id' => $object_id, 'type' => 'Follow',
2064                                 'actor' => $owner['url'],
2065                                 'object' => $profile['url']],
2066                         'instrument' => self::getService(),
2067                         'to' => [$profile['url']]];
2068
2069                 Logger::info('Sending undo to ' . $target . ' for user ' . $uid . ' with id ' . $id);
2070
2071                 $signed = LDSignature::sign($data, $owner);
2072                 return HTTPSignature::transmit($signed, $profile['inbox'], $uid);
2073         }
2074
2075         private static function prependMentions($body, int $uriid, string $authorLink)
2076         {
2077                 $mentions = [];
2078
2079                 foreach (Tag::getByURIId($uriid, [Tag::IMPLICIT_MENTION]) as $tag) {
2080                         $profile = Contact::getByURL($tag['url'], false, ['addr', 'contact-type', 'nick']);
2081                         if (!empty($profile['addr'])
2082                                 && $profile['contact-type'] != Contact::TYPE_COMMUNITY
2083                                 && !strstr($body, $profile['addr'])
2084                                 && !strstr($body, $tag['url'])
2085                                 && $tag['url'] !== $authorLink
2086                         ) {
2087                                 $mentions[] = '@[url=' . $tag['url'] . ']' . $profile['nick'] . '[/url]';
2088                         }
2089                 }
2090
2091                 $mentions[] = $body;
2092
2093                 return implode(' ', $mentions);
2094         }
2095 }