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