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