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