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