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