]> git.mxchange.org Git - friendica.git/blob - src/Protocol/ActivityPub/Transmitter.php
Don't transmit empty conversations
[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'])&& !$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)
1189         {
1190                 $cachekey = 'APDelivery:createActivity:' . $item_id;
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);
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          * @return array of tags
1360          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1361          */
1362         private static function createTagList(array $item): array
1363         {
1364                 $tags = [];
1365
1366                 $terms = Tag::getByURIId($item['uri-id'], [Tag::HASHTAG, Tag::MENTION, Tag::IMPLICIT_MENTION, Tag::EXCLUSIVE_MENTION]);
1367                 foreach ($terms as $term) {
1368                         if ($term['type'] == Tag::HASHTAG) {
1369                                 $url = DI::baseUrl() . '/search?tag=' . urlencode($term['name']);
1370                                 $tags[] = ['type' => 'Hashtag', 'href' => $url, 'name' => '#' . $term['name']];
1371                         } else {
1372                                 $contact = Contact::getByURL($term['url'], false, ['addr']);
1373                                 if (empty($contact)) {
1374                                         continue;
1375                                 }
1376                                 if (!empty($contact['addr'])) {
1377                                         $mention = '@' . $contact['addr'];
1378                                 } else {
1379                                         $mention = '@' . $term['url'];
1380                                 }
1381
1382                                 $tags[] = ['type' => 'Mention', 'href' => $term['url'], 'name' => $mention];
1383                         }
1384                 }
1385
1386                 $announce = self::getAnnounceArray($item);
1387                 // Mention the original author upon commented reshares
1388                 if (!empty($announce['comment'])) {
1389                         $tags[] = ['type' => 'Mention', 'href' => $announce['actor']['url'], 'name' => '@' . $announce['actor']['addr']];
1390                 }
1391
1392                 return $tags;
1393         }
1394
1395         /**
1396          * Adds attachment data to the JSON document
1397          *
1398          * @param array  $item Data of the item that is to be posted
1399          * @param string $type Object type
1400          *
1401          * @return array with attachment data
1402          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1403          */
1404         private static function createAttachmentList(array $item, string $type): array
1405         {
1406                 $attachments = [];
1407
1408                 $uriids = [$item['uri-id']];
1409                 $shared = BBCode::fetchShareAttributes($item['body']);
1410                 if (!empty($shared['guid'])) {
1411                         $shared_item = Post::selectFirst(['uri-id'], ['guid' => $shared['guid']]);
1412                         if (!empty($shared_item['uri-id'])) {
1413                                 $uriids[] = $shared_item['uri-id'];
1414                         }
1415                 }
1416
1417                 $urls = [];
1418                 foreach ($uriids as $uriid) {
1419                         foreach (Post\Media::getByURIId($uriid, [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
1446                 return $attachments;
1447         }
1448
1449         /**
1450          * Callback function to replace a Friendica style mention in a mention for a summary
1451          *
1452          * @param array $match Matching values for the callback
1453          * @return string Replaced mention
1454          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1455          */
1456         private static function mentionAddrCallback(array $match): string
1457         {
1458                 if (empty($match[1])) {
1459                         return '';
1460                 }
1461
1462                 $data = Contact::getByURL($match[1], false, ['addr']);
1463                 if (empty($data['addr'])) {
1464                         return $match[0];
1465                 }
1466
1467                 return '@' . $data['addr'];
1468         }
1469
1470         /**
1471          * Remove image elements since they are added as attachment
1472          *
1473          * @param string $body HTML code
1474          * @return string with removed images
1475          */
1476         private static function removePictures(string $body): string
1477         {
1478                 // Simplify image codes
1479                 $body = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '[img]$3[/img]', $body);
1480                 $body = preg_replace("/\[img\=(.*?)\](.*?)\[\/img\]/ism", '[img]$1[/img]', $body);
1481
1482                 // Now remove local links
1483                 $body = preg_replace_callback(
1484                         '/\[url=([^\[\]]*)\]\[img\](.*)\[\/img\]\[\/url\]/Usi',
1485                         function ($match) {
1486                                 // We remove the link when it is a link to a local photo page
1487                                 if (Photo::isLocalPage($match[1])) {
1488                                         return '';
1489                                 }
1490                                 // otherwise we just return the link
1491                                 return '[url]' . $match[1] . '[/url]';
1492                         },
1493                         $body
1494                 );
1495
1496                 // Remove all pictures
1497                 $body = preg_replace("/\[img\]([^\[\]]*)\[\/img\]/Usi", '', $body);
1498
1499                 return $body;
1500         }
1501
1502         /**
1503          * Returns if the post contains sensitive content ("nsfw")
1504          *
1505          * @param integer $uri_id URI id
1506          * @return boolean Whether URI id was found
1507          * @throws \Exception
1508          */
1509         private static function isSensitive(int $uri_id): bool
1510         {
1511                 return DBA::exists('tag-view', ['uri-id' => $uri_id, 'name' => 'nsfw', 'type' => Tag::HASHTAG]);
1512         }
1513
1514         /**
1515          * Creates event data
1516          *
1517          * @param array $item Item array
1518          * @return array with the event data
1519          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1520          */
1521         private static function createEvent(array $item): array
1522         {
1523                 $event = [];
1524                 $event['name'] = $item['event-summary'];
1525                 $event['content'] = BBCode::convertForUriId($item['uri-id'], $item['event-desc'], BBCode::ACTIVITYPUB);
1526                 $event['startTime'] = DateTimeFormat::utc($item['event-start'], 'c');
1527
1528                 if (!$item['event-nofinish']) {
1529                         $event['endTime'] = DateTimeFormat::utc($item['event-finish'], 'c');
1530                 }
1531
1532                 if (!empty($item['event-location'])) {
1533                         $item['location'] = $item['event-location'];
1534                         $event['location'] = self::createLocation($item);
1535                 }
1536
1537                 // 2021.12: Backward compatibility value, all the events now "adjust" to the viewer timezone
1538                 $event['dfrn:adjust'] = true;
1539
1540                 return $event;
1541         }
1542
1543         /**
1544          * Creates a note/article object array
1545          *
1546          * @param array $item
1547          * @return array with the object data
1548          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1549          * @throws \ImagickException
1550          */
1551         public static function createNote(array $item): array
1552         {
1553                 if (empty($item)) {
1554                         return [];
1555                 }
1556
1557                 // We are treating posts differently when they are directed to a community.
1558                 // This is done to better support Lemmy. Most of the changes should work with other systems as well.
1559                 // But to not risk compatibility issues we currently perform the changes only for communities.
1560                 if ($item['gravity'] == GRAVITY_PARENT) {
1561                         $isCommunityPost = !empty(Tag::getByURIId($item['uri-id'], [Tag::EXCLUSIVE_MENTION]));
1562                         $links = Post\Media::getByURIId($item['uri-id'], [Post\Media::HTML]);
1563                         if ($isCommunityPost && (count($links) == 1)) {
1564                                 $link = $links[0]['url'];
1565                         }
1566                 } else {
1567                         $isCommunityPost = false;
1568                 }
1569
1570                 if ($item['event-type'] == 'event') {
1571                         $type = 'Event';
1572                 } elseif (!empty($item['title'])) {
1573                         if (!$isCommunityPost || empty($link)) {
1574                                 $type = 'Article';
1575                         } else {
1576                                 // "Page" is used by Lemmy for posts that contain an external link
1577                                 $type = 'Page';
1578                         }
1579                 } else {
1580                         $type = 'Note';
1581                 }
1582
1583                 if ($item['deleted']) {
1584                         $type = 'Tombstone';
1585                 }
1586
1587                 $data = [];
1588                 $data['id'] = $item['uri'];
1589                 $data['type'] = $type;
1590
1591                 if ($item['deleted']) {
1592                         return $data;
1593                 }
1594
1595                 $data['summary'] = BBCode::toPlaintext(BBCode::getAbstract($item['body'], Protocol::ACTIVITYPUB));
1596
1597                 if ($item['uri'] != $item['thr-parent']) {
1598                         $data['inReplyTo'] = $item['thr-parent'];
1599                 } else {
1600                         $data['inReplyTo'] = null;
1601                 }
1602
1603                 $data['diaspora:guid'] = $item['guid'];
1604                 $data['published'] = DateTimeFormat::utc($item['created'] . '+00:00', DateTimeFormat::ATOM);
1605
1606                 if ($item['created'] != $item['edited']) {
1607                         $data['updated'] = DateTimeFormat::utc($item['edited'] . '+00:00', DateTimeFormat::ATOM);
1608                 }
1609
1610                 $data['url'] = $link ?? $item['plink'];
1611                 $data['attributedTo'] = $item['author-link'];
1612                 $data['sensitive'] = self::isSensitive($item['uri-id']);
1613
1614                 if (!empty($item['conversation']) && ($item['conversation'] != './')) {
1615                         $data['conversation'] = $data['context'] = $item['conversation'];
1616                 }
1617
1618                 if (!empty($item['title'])) {
1619                         $data['name'] = BBCode::toPlaintext($item['title'], false);
1620                 }
1621
1622                 $permission_block = self::createPermissionBlockForItem($item, false);
1623
1624                 $body = $item['body'];
1625
1626                 if ($type == 'Note') {
1627                         $body = $item['raw-body'] ?? self::removePictures($body);
1628                 }
1629
1630                 /**
1631                  * @todo Improve the automated summary
1632                  * This part is currently deactivated. The automated summary seems to be more
1633                  * confusing than helping. But possibly we will find a better way.
1634                  * So the code is left here for now as a reminder
1635                  *
1636                  * } elseif (($type == 'Article') && empty($data['summary'])) {
1637                  *              $regexp = "/[@!]\[url\=([^\[\]]*)\].*?\[\/url\]/ism";
1638                  *              $summary = preg_replace_callback($regexp, ['self', 'mentionAddrCallback'], $body);
1639                  *              $data['summary'] = BBCode::toPlaintext(Plaintext::shorten(self::removePictures($summary), 1000));
1640                  * }
1641                  */
1642
1643                 if (empty($item['uid']) || !Feature::isEnabled($item['uid'], 'explicit_mentions')) {
1644                         $body = self::prependMentions($body, $item['uri-id'], $item['author-link']);
1645                 }
1646
1647                 if ($type == 'Event') {
1648                         $data = array_merge($data, self::createEvent($item));
1649                 } else {
1650                         if ($isCommunityPost) {
1651                                 // For community posts we remove the visible "!user@domain.tld".
1652                                 // This improves the look at systems like Lemmy.
1653                                 // Also in the future we should control the community delivery via other methods.
1654                                 $body = preg_replace("/!\[url\=[^\[\]]*\][^\[\]]*\[\/url\]/ism", '', $body);
1655                         }
1656
1657                         if ($type == 'Page') {
1658                                 // When we transmit "Page" posts we have to remove the attachment.
1659                                 // The attachment contains the link that we already transmit in the "url" field.
1660                                 $body = preg_replace("/\s*\[attachment .*?\].*?\[\/attachment\]\s*/ism", '', $body);
1661                         }
1662
1663                         $body = BBCode::setMentionsToNicknames($body);
1664
1665                         $data['content'] = BBCode::convertForUriId($item['uri-id'], $body, BBCode::ACTIVITYPUB);
1666                 }
1667
1668                 // The regular "content" field does contain a minimized HTML. This is done since systems like
1669                 // Mastodon has got problems with - for example - embedded pictures.
1670                 // The contentMap does contain the unmodified HTML.
1671                 $language = self::getLanguage($item);
1672                 if (!empty($language)) {
1673                         $richbody = BBCode::setMentionsToNicknames($item['body'] ?? '');
1674                         $richbody = BBCode::removeAttachment($richbody);
1675
1676                         $data['contentMap'][$language] = BBCode::convertForUriId($item['uri-id'], $richbody, BBCode::EXTERNAL);
1677                 }
1678
1679                 $data['source'] = ['content' => $item['body'], 'mediaType' => "text/bbcode"];
1680
1681                 if (!empty($item['signed_text']) && ($item['uri'] != $item['thr-parent'])) {
1682                         $data['diaspora:comment'] = $item['signed_text'];
1683                 }
1684
1685                 $data['attachment'] = self::createAttachmentList($item, $type);
1686                 $data['tag'] = self::createTagList($item);
1687
1688                 if (empty($data['location']) && (!empty($item['coord']) || !empty($item['location']))) {
1689                         $data['location'] = self::createLocation($item);
1690                 }
1691
1692                 if (!empty($item['app'])) {
1693                         $data['generator'] = ['type' => 'Application', 'name' => $item['app']];
1694                 }
1695
1696                 $data = array_merge($data, $permission_block);
1697
1698                 return $data;
1699         }
1700
1701         /**
1702          * Fetches the language from the post, the user or the system.
1703          *
1704          * @param array $item
1705          * @return string language string
1706          */
1707         private static function getLanguage(array $item): string
1708         {
1709                 // Try to fetch the language from the post itself
1710                 if (!empty($item['language'])) {
1711                         $languages = array_keys(json_decode($item['language'], true));
1712                         if (!empty($languages[0])) {
1713                                 return $languages[0];
1714                         }
1715                 }
1716
1717                 // Otherwise use the user's language
1718                 if (!empty($item['uid'])) {
1719                         $user = DBA::selectFirst('user', ['language'], ['uid' => $item['uid']]);
1720                         if (!empty($user['language'])) {
1721                                 return $user['language'];
1722                         }
1723                 }
1724
1725                 // And finally just use the system language
1726                 return DI::config()->get('system', 'language');
1727         }
1728
1729         /**
1730          * Creates an an "add tag" entry
1731          *
1732          * @param array $item Item array
1733          * @param array $activity activity data
1734          * @return array with activity data for adding tags
1735          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1736          * @throws \ImagickException
1737          */
1738         private static function createAddTag(array $item, array $activity): array
1739         {
1740                 $object = XML::parseString($item['object']);
1741                 $target = XML::parseString($item['target']);
1742
1743                 $activity['diaspora:guid'] = $item['guid'];
1744                 $activity['actor'] = $item['author-link'];
1745                 $activity['target'] = (string)$target->id;
1746                 $activity['summary'] = BBCode::toPlaintext($item['body']);
1747                 $activity['object'] = ['id' => (string)$object->id, 'type' => 'tag', 'name' => (string)$object->title, 'content' => (string)$object->content];
1748
1749                 return $activity;
1750         }
1751
1752         /**
1753          * Creates an announce object entry
1754          *
1755          * @param array $item Item array
1756          * @param array $activity activity data
1757          * @return array with activity data
1758          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1759          * @throws \ImagickException
1760          */
1761         private static function createAnnounce(array $item, array $activity): array
1762         {
1763                 $orig_body = $item['body'];
1764                 $announce = self::getAnnounceArray($item);
1765                 if (empty($announce)) {
1766                         $activity['type'] = 'Create';
1767                         $activity['object'] = self::createNote($item);
1768                         return $activity;
1769                 }
1770
1771                 if (empty($announce['comment'])) {
1772                         // Pure announce, without a quote
1773                         $activity['type'] = 'Announce';
1774                         $activity['object'] = $announce['object']['uri'];
1775                         return $activity;
1776                 }
1777
1778                 // Quote
1779                 $activity['type'] = 'Create';
1780                 $item['body'] = $announce['comment'] . "\n" . $announce['object']['plink'];
1781                 $activity['object'] = self::createNote($item);
1782
1783                 /// @todo Finally descide how to implement this in AP. This is a possible way:
1784                 $activity['object']['attachment'][] = self::createNote($announce['object']);
1785
1786                 $activity['object']['source']['content'] = $orig_body;
1787                 return $activity;
1788         }
1789
1790         /**
1791          * Return announce related data if the item is an annunce
1792          *
1793          * @param array $item
1794          * @return array Announcement array
1795          */
1796         public static function getAnnounceArray(array $item): array
1797         {
1798                 $reshared = Item::getShareArray($item);
1799                 if (empty($reshared['guid'])) {
1800                         return [];
1801                 }
1802
1803                 $reshared_item = Post::selectFirst(Item::DELIVER_FIELDLIST, ['guid' => $reshared['guid']]);
1804                 if (!DBA::isResult($reshared_item)) {
1805                         return [];
1806                 }
1807
1808                 if (!in_array($reshared_item['network'], [Protocol::ACTIVITYPUB, Protocol::DFRN])) {
1809                         return [];
1810                 }
1811
1812                 $profile = APContact::getByURL($reshared_item['author-link'], false);
1813                 if (empty($profile)) {
1814                         return [];
1815                 }
1816
1817                 return ['object' => $reshared_item, 'actor' => $profile, 'comment' => $reshared['comment']];
1818         }
1819
1820         /**
1821          * Checks if the provided item array is an announce
1822          *
1823          * @param array $item Item array
1824          * @return boolean Whether item is an announcement
1825          */
1826         public static function isAnnounce(array $item): bool
1827         {
1828                 if (!empty($item['verb']) && ($item['verb'] == Activity::ANNOUNCE)) {
1829                         return true;
1830                 }
1831
1832                 $announce = self::getAnnounceArray($item);
1833                 if (empty($announce)) {
1834                         return false;
1835                 }
1836
1837                 return empty($announce['comment']);
1838         }
1839
1840         /**
1841          * Creates an activity id for a given contact id
1842          *
1843          * @param integer $cid Contact ID of target
1844          *
1845          * @return bool|string activity id
1846          */
1847         public static function activityIDFromContact(int $cid)
1848         {
1849                 $contact = DBA::selectFirst('contact', ['uid', 'id', 'created'], ['id' => $cid]);
1850                 if (!DBA::isResult($contact)) {
1851                         return false;
1852                 }
1853
1854                 $hash = hash('ripemd128', $contact['uid'].'-'.$contact['id'].'-'.$contact['created']);
1855                 $uuid = substr($hash, 0, 8). '-' . substr($hash, 8, 4) . '-' . substr($hash, 12, 4) . '-' . substr($hash, 16, 4) . '-' . substr($hash, 20, 12);
1856                 return DI::baseUrl() . '/activity/' . $uuid;
1857         }
1858
1859         /**
1860          * Transmits a contact suggestion to a given inbox
1861          *
1862          * @param integer $uid           User ID
1863          * @param string  $inbox         Target inbox
1864          * @param integer $suggestion_id Suggestion ID
1865          * @return boolean was the transmission successful?
1866          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1867          */
1868         public static function sendContactSuggestion(int $uid, string $inbox, int $suggestion_id): bool
1869         {
1870                 $owner = User::getOwnerDataById($uid);
1871
1872                 $suggestion = DI::fsuggest()->selectOneById($suggestion_id);
1873
1874                 $data = [
1875                         '@context' => ActivityPub::CONTEXT,
1876                         'id' => DI::baseUrl() . '/activity/' . System::createGUID(),
1877                         'type' => 'Announce',
1878                         'actor' => $owner['url'],
1879                         'object' => $suggestion->url,
1880                         'content' => $suggestion->note,
1881                         'instrument' => self::getService(),
1882                         'to' => [ActivityPub::PUBLIC_COLLECTION],
1883                         'cc' => []
1884                 ];
1885
1886                 $signed = LDSignature::sign($data, $owner);
1887
1888                 Logger::info('Deliver profile deletion for user ' . $uid . ' to ' . $inbox . ' via ActivityPub');
1889                 return HTTPSignature::transmit($signed, $inbox, $uid);
1890         }
1891
1892         /**
1893          * Transmits a profile relocation to a given inbox
1894          *
1895          * @param integer $uid   User ID
1896          * @param string  $inbox Target inbox
1897          * @return boolean was the transmission successful?
1898          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1899          */
1900         public static function sendProfileRelocation(int $uid, string $inbox): bool
1901         {
1902                 $owner = User::getOwnerDataById($uid);
1903
1904                 $data = [
1905                         '@context' => ActivityPub::CONTEXT,
1906                         'id' => DI::baseUrl() . '/activity/' . System::createGUID(),
1907                         'type' => 'dfrn:relocate',
1908                         'actor' => $owner['url'],
1909                         'object' => $owner['url'],
1910                         'published' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
1911                         'instrument' => self::getService(),
1912                         'to' => [ActivityPub::PUBLIC_COLLECTION],
1913                         'cc' => []
1914                 ];
1915
1916                 $signed = LDSignature::sign($data, $owner);
1917
1918                 Logger::info('Deliver profile relocation for user ' . $uid . ' to ' . $inbox . ' via ActivityPub');
1919                 return HTTPSignature::transmit($signed, $inbox, $uid);
1920         }
1921
1922         /**
1923          * Transmits a profile deletion to a given inbox
1924          *
1925          * @param integer $uid   User ID
1926          * @param string  $inbox Target inbox
1927          * @return boolean was the transmission successful?
1928          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1929          */
1930         public static function sendProfileDeletion(int $uid, string $inbox): bool
1931         {
1932                 $owner = User::getOwnerDataById($uid);
1933
1934                 if (empty($owner)) {
1935                         Logger::error('No owner data found, the deletion message cannot be processed.', ['user' => $uid]);
1936                         return false;
1937                 }
1938
1939                 if (empty($owner['uprvkey'])) {
1940                         Logger::error('No private key for owner found, the deletion message cannot be processed.', ['user' => $uid]);
1941                         return false;
1942                 }
1943
1944                 $data = ['@context' => ActivityPub::CONTEXT,
1945                         'id' => DI::baseUrl() . '/activity/' . System::createGUID(),
1946                         'type' => 'Delete',
1947                         'actor' => $owner['url'],
1948                         'object' => $owner['url'],
1949                         'published' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
1950                         'instrument' => self::getService(),
1951                         'to' => [ActivityPub::PUBLIC_COLLECTION],
1952                         'cc' => []];
1953
1954                 $signed = LDSignature::sign($data, $owner);
1955
1956                 Logger::info('Deliver profile deletion for user ' . $uid . ' to ' . $inbox . ' via ActivityPub');
1957                 return HTTPSignature::transmit($signed, $inbox, $uid);
1958         }
1959
1960         /**
1961          * Transmits a profile change to a given inbox
1962          *
1963          * @param integer $uid   User ID
1964          * @param string  $inbox Target inbox
1965          * @return boolean was the transmission successful?
1966          * @throws HTTPException\InternalServerErrorException
1967          * @throws HTTPException\NotFoundException
1968          * @throws \ImagickException
1969          */
1970         public static function sendProfileUpdate(int $uid, string $inbox): bool
1971         {
1972                 $owner = User::getOwnerDataById($uid);
1973                 $profile = APContact::getByURL($owner['url']);
1974
1975                 $data = ['@context' => ActivityPub::CONTEXT,
1976                         'id' => DI::baseUrl() . '/activity/' . System::createGUID(),
1977                         'type' => 'Update',
1978                         'actor' => $owner['url'],
1979                         'object' => self::getProfile($uid),
1980                         'published' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
1981                         'instrument' => self::getService(),
1982                         'to' => [$profile['followers']],
1983                         'cc' => []];
1984
1985                 $signed = LDSignature::sign($data, $owner);
1986
1987                 Logger::info('Deliver profile update for user ' . $uid . ' to ' . $inbox . ' via ActivityPub');
1988                 return HTTPSignature::transmit($signed, $inbox, $uid);
1989         }
1990
1991         /**
1992          * Transmits a given activity to a target
1993          *
1994          * @param string  $activity Type name
1995          * @param string  $target   Target profile
1996          * @param integer $uid      User ID
1997          * @param string  $id Activity-identifier
1998          * @return bool
1999          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2000          * @throws \ImagickException
2001          * @throws \Exception
2002          */
2003         public static function sendActivity(string $activity, string $target, int $uid, string $id = ''): bool
2004         {
2005                 $profile = APContact::getByURL($target);
2006                 if (empty($profile['inbox'])) {
2007                         Logger::warning('No inbox found for target', ['target' => $target, 'profile' => $profile]);
2008                         return false;
2009                 }
2010
2011                 $owner = User::getOwnerDataById($uid);
2012
2013                 if (empty($id)) {
2014                         $id = DI::baseUrl() . '/activity/' . System::createGUID();
2015                 }
2016
2017                 $data = [
2018                         '@context' => ActivityPub::CONTEXT,
2019                         'id' => $id,
2020                         'type' => $activity,
2021                         'actor' => $owner['url'],
2022                         'object' => $profile['url'],
2023                         'instrument' => self::getService(),
2024                         'to' => [$profile['url']],
2025                 ];
2026
2027                 Logger::info('Sending activity ' . $activity . ' to ' . $target . ' for user ' . $uid);
2028
2029                 $signed = LDSignature::sign($data, $owner);
2030                 return HTTPSignature::transmit($signed, $profile['inbox'], $uid);
2031         }
2032
2033         /**
2034          * Transmits a "follow object" activity to a target
2035          * This is a preparation for sending automated "follow" requests when receiving "Announce" messages
2036          *
2037          * @param string  $object Object URL
2038          * @param string  $target Target profile
2039          * @param integer $uid    User ID
2040          * @return bool
2041          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2042          * @throws \ImagickException
2043          * @throws \Exception
2044          */
2045         public static function sendFollowObject(string $object, string $target, int $uid = 0): bool
2046         {
2047                 $profile = APContact::getByURL($target);
2048                 if (empty($profile['inbox'])) {
2049                         Logger::warning('No inbox found for target', ['target' => $target, 'profile' => $profile]);
2050                         return false;
2051                 }
2052
2053                 if (empty($uid)) {
2054                         // Fetch the list of administrators
2055                         $admin_mail = explode(',', str_replace(' ', '', DI::config()->get('config', 'admin_email')));
2056
2057                         // We need to use some user as a sender. It doesn't care who it will send. We will use an administrator account.
2058                         $condition = ['verified' => true, 'blocked' => false, 'account_removed' => false, 'account_expired' => false, 'email' => $admin_mail];
2059                         $first_user = DBA::selectFirst('user', ['uid'], $condition);
2060                         $uid = $first_user['uid'];
2061                 }
2062
2063                 $condition = ['verb' => Activity::FOLLOW, 'uid' => 0, 'parent-uri' => $object,
2064                         'author-id' => Contact::getPublicIdByUserId($uid)];
2065                 if (Post::exists($condition)) {
2066                         Logger::info('Follow for ' . $object . ' for user ' . $uid . ' does already exist.');
2067                         return false;
2068                 }
2069
2070                 $owner = User::getOwnerDataById($uid);
2071
2072                 $data = [
2073                         '@context' => ActivityPub::CONTEXT,
2074                         'id' => DI::baseUrl() . '/activity/' . System::createGUID(),
2075                         'type' => 'Follow',
2076                         'actor' => $owner['url'],
2077                         'object' => $object,
2078                         'instrument' => self::getService(),
2079                         'to' => [$profile['url']],
2080                 ];
2081
2082                 Logger::info('Sending follow ' . $object . ' to ' . $target . ' for user ' . $uid);
2083
2084                 $signed = LDSignature::sign($data, $owner);
2085                 return HTTPSignature::transmit($signed, $profile['inbox'], $uid);
2086         }
2087
2088         /**
2089          * Transmit a message that the contact request had been accepted
2090          *
2091          * @param string  $target Target profile
2092          * @param string  $id Object id
2093          * @param integer $uid    User ID
2094          * @return void
2095          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2096          * @throws \ImagickException
2097          */
2098         public static function sendContactAccept(string $target, string $id, int $uid)
2099         {
2100                 $profile = APContact::getByURL($target);
2101                 if (empty($profile['inbox'])) {
2102                         Logger::warning('No inbox found for target', ['target' => $target, 'profile' => $profile]);
2103                         return;
2104                 }
2105
2106                 $owner = User::getOwnerDataById($uid);
2107                 $data = [
2108                         '@context' => ActivityPub::CONTEXT,
2109                         'id' => DI::baseUrl() . '/activity/' . System::createGUID(),
2110                         'type' => 'Accept',
2111                         'actor' => $owner['url'],
2112                         'object' => [
2113                                 'id' => $id,
2114                                 'type' => 'Follow',
2115                                 'actor' => $profile['url'],
2116                                 'object' => $owner['url']
2117                         ],
2118                         'instrument' => self::getService(),
2119                         'to' => [$profile['url']],
2120                 ];
2121
2122                 Logger::debug('Sending accept to ' . $target . ' for user ' . $uid . ' with id ' . $id);
2123
2124                 $signed = LDSignature::sign($data, $owner);
2125                 HTTPSignature::transmit($signed, $profile['inbox'], $uid);
2126         }
2127
2128         /**
2129          * Reject a contact request or terminates the contact relation
2130          *
2131          * @param string $target   Target profile
2132          * @param string $objectId Object id
2133          * @param int    $uid      User ID
2134          * @return bool Operation success
2135          * @throws HTTPException\InternalServerErrorException
2136          * @throws \ImagickException
2137          */
2138         public static function sendContactReject(string $target, string $objectId, int $uid): bool
2139         {
2140                 $profile = APContact::getByURL($target);
2141                 if (empty($profile['inbox'])) {
2142                         Logger::warning('No inbox found for target', ['target' => $target, 'profile' => $profile]);
2143                         return false;
2144                 }
2145
2146                 $owner = User::getOwnerDataById($uid);
2147                 $data = [
2148                         '@context' => ActivityPub::CONTEXT,
2149                         'id' => DI::baseUrl() . '/activity/' . System::createGUID(),
2150                         'type' => 'Reject',
2151                         'actor'  => $owner['url'],
2152                         'object' => [
2153                                 'id' => $objectId,
2154                                 'type' => 'Follow',
2155                                 'actor' => $profile['url'],
2156                                 'object' => $owner['url']
2157                         ],
2158                         'instrument' => self::getService(),
2159                         'to' => [$profile['url']],
2160                 ];
2161
2162                 Logger::debug('Sending reject to ' . $target . ' for user ' . $uid . ' with id ' . $objectId);
2163
2164                 $signed = LDSignature::sign($data, $owner);
2165                 return HTTPSignature::transmit($signed, $profile['inbox'], $uid);
2166         }
2167
2168         /**
2169          * Transmits a message that we don't want to follow this contact anymore
2170          *
2171          * @param string  $target Target profile
2172          * @param integer $cid    Contact id
2173          * @param integer $uid    User ID
2174          * @return bool success
2175          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2176          * @throws \ImagickException
2177          * @throws \Exception
2178          */
2179         public static function sendContactUndo(string $target, int $cid, int $uid): bool
2180         {
2181                 $profile = APContact::getByURL($target);
2182                 if (empty($profile['inbox'])) {
2183                         Logger::warning('No inbox found for target', ['target' => $target, 'profile' => $profile]);
2184                         return false;
2185                 }
2186
2187                 $object_id = self::activityIDFromContact($cid);
2188                 if (empty($object_id)) {
2189                         return false;
2190                 }
2191
2192                 $objectId = DI::baseUrl() . '/activity/' . System::createGUID();
2193
2194                 $owner = User::getOwnerDataById($uid);
2195                 $data = [
2196                         '@context' => ActivityPub::CONTEXT,
2197                         'id' => $objectId,
2198                         'type' => 'Undo',
2199                         'actor' => $owner['url'],
2200                         'object' => [
2201                                 'id' => $object_id,
2202                                 'type' => 'Follow',
2203                                 'actor' => $owner['url'],
2204                                 'object' => $profile['url']
2205                         ],
2206                         'instrument' => self::getService(),
2207                         'to' => [$profile['url']],
2208                 ];
2209
2210                 Logger::info('Sending undo to ' . $target . ' for user ' . $uid . ' with id ' . $objectId);
2211
2212                 $signed = LDSignature::sign($data, $owner);
2213                 return HTTPSignature::transmit($signed, $profile['inbox'], $uid);
2214         }
2215
2216         /**
2217          * Prepends mentions (@) to $body variable
2218          *
2219          * @param string $body HTML code
2220          * @param int    $uriId
2221          * @param string $authorLink Author link
2222          * @return string HTML code with prepended mentions
2223          */
2224         private static function prependMentions(string $body, int $uriid, string $authorLink): string
2225         {
2226                 $mentions = [];
2227
2228                 foreach (Tag::getByURIId($uriid, [Tag::IMPLICIT_MENTION]) as $tag) {
2229                         $profile = Contact::getByURL($tag['url'], false, ['addr', 'contact-type', 'nick']);
2230                         if (!empty($profile['addr'])
2231                                 && $profile['contact-type'] != Contact::TYPE_COMMUNITY
2232                                 && !strstr($body, $profile['addr'])
2233                                 && !strstr($body, $tag['url'])
2234                                 && $tag['url'] !== $authorLink
2235                         ) {
2236                                 $mentions[] = '@[url=' . $tag['url'] . ']' . $profile['nick'] . '[/url]';
2237                         }
2238                 }
2239
2240                 $mentions[] = $body;
2241
2242                 return implode(' ', $mentions);
2243         }
2244 }