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