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