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