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