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