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