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