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