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