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