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