]> git.mxchange.org Git - friendica.git/blob - src/Protocol/ActivityPub/Transmitter.php
Improved workerqueue 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                         $condition = ['item-uri' => $item['uri'], 'protocol' => Conversation::PARCEL_ACTIVITYPUB];
1236                         $conversation = DBA::selectFirst('conversation', ['source'], $condition);
1237                         if (!$item['origin'] && DBA::isResult($conversation)) {
1238                                 $data = json_decode($conversation['source'], true);
1239                                 if (!empty($data['type'])) {
1240                                         if (in_array($data['type'], ['Create', 'Update'])) {
1241                                                 if ($object_mode) {
1242                                                         unset($data['@context']);
1243                                                         unset($data['signature']);
1244                                                 }
1245                                                 Logger::info('Return stored conversation', ['item' => $item_id]);
1246                                                 return $data;
1247                                         } elseif (in_array('as:' . $data['type'], Receiver::CONTENT_TYPES)) {
1248                                                 if (!empty($data['@context'])) {
1249                                                         $context = $data['@context'];
1250                                                         unset($data['@context']);
1251                                                 }
1252                                                 unset($data['actor']);
1253                                                 $object = $data;
1254                                         }
1255                                 }
1256                         }
1257                 }
1258
1259                 $type = self::getTypeOfItem($item);
1260
1261                 if (!$object_mode) {
1262                         $data = ['@context' => $context ?? ActivityPub::CONTEXT];
1263
1264                         if ($item['deleted'] && ($item['gravity'] == GRAVITY_ACTIVITY)) {
1265                                 $type = 'Undo';
1266                         } elseif ($item['deleted']) {
1267                                 $type = 'Delete';
1268                         }
1269                 } else {
1270                         $data = [];
1271                 }
1272
1273                 if ($type == 'Delete') {
1274                         $data['id'] = Item::newURI($item['guid']) . '/' . $type;;
1275                 } elseif (($item['gravity'] == GRAVITY_ACTIVITY) && ($type != 'Undo')) {
1276                         $data['id'] = $item['uri'];
1277                 } else {
1278                         $data['id'] = $item['uri'] . '/' . $type;
1279                 }
1280
1281                 $data['type'] = $type;
1282
1283                 if (($type != 'Announce') || ($item['gravity'] != GRAVITY_PARENT)) {
1284                         $data['actor'] = $item['author-link'];
1285                 } else {
1286                         $data['actor'] = $item['owner-link'];
1287                 }
1288
1289                 $data['published'] = DateTimeFormat::utc($item['created'] . '+00:00', DateTimeFormat::ATOM);
1290
1291                 $data['instrument'] = self::getService();
1292
1293                 $data = array_merge($data, self::createPermissionBlockForItem($item, false));
1294
1295                 if (in_array($data['type'], ['Create', 'Update', 'Delete'])) {
1296                         $data['object'] = $object ?? self::createNote($item);
1297                         $data['published'] = DateTimeFormat::utcNow(DateTimeFormat::ATOM);
1298                 } elseif ($data['type'] == 'Add') {
1299                         $data = self::createAddTag($item, $data);
1300                 } elseif ($data['type'] == 'Announce') {
1301                         if ($item['verb'] == ACTIVITY::ANNOUNCE) {
1302                                 $data['object'] = $item['thr-parent'];
1303                         } else {
1304                                 $data = self::createAnnounce($item, $data);
1305                         }
1306                 } elseif ($data['type'] == 'Follow') {
1307                         $data['object'] = $item['parent-uri'];
1308                 } elseif ($data['type'] == 'Undo') {
1309                         $data['object'] = self::createActivityFromItem($item_id, true);
1310                 } else {
1311                         $data['diaspora:guid'] = $item['guid'];
1312                         if (!empty($item['signed_text'])) {
1313                                 $data['diaspora:like'] = $item['signed_text'];
1314                         }
1315                         $data['object'] = $item['thr-parent'];
1316                 }
1317
1318                 if (!empty($item['contact-uid'])) {
1319                         $uid = $item['contact-uid'];
1320                 } else {
1321                         $uid = $item['uid'];
1322                 }
1323
1324                 $owner = User::getOwnerDataById($uid);
1325
1326                 Logger::info('Fetched activity', ['item' => $item_id, 'uid' => $uid]);
1327
1328                 // We don't sign if we aren't the actor. This is important for relaying content especially for forums
1329                 if (!$object_mode && !empty($owner) && ($data['actor'] == $owner['url'])) {
1330                         return LDSignature::sign($data, $owner);
1331                 } else {
1332                         return $data;
1333                 }
1334
1335                 /// @todo Create "conversation" entry
1336         }
1337
1338         /**
1339          * Creates a location entry for a given item array
1340          *
1341          * @param array $item Item array
1342          * @return array with location array
1343          */
1344         private static function createLocation(array $item): array
1345         {
1346                 $location = ['type' => 'Place'];
1347
1348                 if (!empty($item['location'])) {
1349                         $location['name'] = $item['location'];
1350                 }
1351
1352                 $coord = [];
1353
1354                 if (empty($item['coord'])) {
1355                         $coord = Map::getCoordinates($item['location']);
1356                 } else {
1357                         $coords = explode(' ', $item['coord']);
1358                         if (count($coords) == 2) {
1359                                 $coord = ['lat' => $coords[0], 'lon' => $coords[1]];
1360                         }
1361                 }
1362
1363                 if (!empty($coord['lat']) && !empty($coord['lon'])) {
1364                         $location['latitude'] = $coord['lat'];
1365                         $location['longitude'] = $coord['lon'];
1366                 }
1367
1368                 return $location;
1369         }
1370
1371         /**
1372          * Returns a tag array for a given item array
1373          *
1374          * @param array $item Item array
1375          * @return array of tags
1376          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1377          */
1378         private static function createTagList(array $item): array
1379         {
1380                 $tags = [];
1381
1382                 $terms = Tag::getByURIId($item['uri-id'], [Tag::HASHTAG, Tag::MENTION, Tag::IMPLICIT_MENTION, Tag::EXCLUSIVE_MENTION]);
1383                 foreach ($terms as $term) {
1384                         if ($term['type'] == Tag::HASHTAG) {
1385                                 $url = DI::baseUrl() . '/search?tag=' . urlencode($term['name']);
1386                                 $tags[] = ['type' => 'Hashtag', 'href' => $url, 'name' => '#' . $term['name']];
1387                         } else {
1388                                 $contact = Contact::getByURL($term['url'], false, ['addr']);
1389                                 if (empty($contact)) {
1390                                         continue;
1391                                 }
1392                                 if (!empty($contact['addr'])) {
1393                                         $mention = '@' . $contact['addr'];
1394                                 } else {
1395                                         $mention = '@' . $term['url'];
1396                                 }
1397
1398                                 $tags[] = ['type' => 'Mention', 'href' => $term['url'], 'name' => $mention];
1399                         }
1400                 }
1401
1402                 $announce = self::getAnnounceArray($item);
1403                 // Mention the original author upon commented reshares
1404                 if (!empty($announce['comment'])) {
1405                         $tags[] = ['type' => 'Mention', 'href' => $announce['actor']['url'], 'name' => '@' . $announce['actor']['addr']];
1406                 }
1407
1408                 return $tags;
1409         }
1410
1411         /**
1412          * Adds attachment data to the JSON document
1413          *
1414          * @param array  $item Data of the item that is to be posted
1415          * @param string $type Object type
1416          *
1417          * @return array with attachment data
1418          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1419          */
1420         private static function createAttachmentList(array $item, string $type): array
1421         {
1422                 $attachments = [];
1423
1424                 $uriids = [$item['uri-id']];
1425                 $shared = BBCode::fetchShareAttributes($item['body']);
1426                 if (!empty($shared['guid'])) {
1427                         $shared_item = Post::selectFirst(['uri-id'], ['guid' => $shared['guid']]);
1428                         if (!empty($shared_item['uri-id'])) {
1429                                 $uriids[] = $shared_item['uri-id'];
1430                         }
1431                 }
1432
1433                 $urls = [];
1434                 foreach ($uriids as $uriid) {
1435                         foreach (Post\Media::getByURIId($uriid, [Post\Media::AUDIO, Post\Media::IMAGE, Post\Media::VIDEO, Post\Media::DOCUMENT, Post\Media::TORRENT]) as $attachment) {
1436                                 if (in_array($attachment['url'], $urls)) {
1437                                         continue;
1438                                 }
1439                                 $urls[] = $attachment['url'];
1440
1441                                 $attach = ['type' => 'Document',
1442                                         'mediaType' => $attachment['mimetype'],
1443                                         'url' => $attachment['url'],
1444                                         'name' => $attachment['description']];
1445
1446                                 if (!empty($attachment['height'])) {
1447                                         $attach['height'] = $attachment['height'];
1448                                 }
1449
1450                                 if (!empty($attachment['width'])) {
1451                                         $attach['width'] = $attachment['width'];
1452                                 }
1453
1454                                 if (!empty($attachment['preview'])) {
1455                                         $attach['image'] = $attachment['preview'];
1456                                 }
1457
1458                                 $attachments[] = $attach;
1459                         }
1460                 }
1461
1462                 return $attachments;
1463         }
1464
1465         /**
1466          * Callback function to replace a Friendica style mention in a mention for a summary
1467          *
1468          * @param array $match Matching values for the callback
1469          * @return string Replaced mention
1470          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1471          */
1472         private static function mentionAddrCallback(array $match): string
1473         {
1474                 if (empty($match[1])) {
1475                         return '';
1476                 }
1477
1478                 $data = Contact::getByURL($match[1], false, ['addr']);
1479                 if (empty($data['addr'])) {
1480                         return $match[0];
1481                 }
1482
1483                 return '@' . $data['addr'];
1484         }
1485
1486         /**
1487          * Remove image elements since they are added as attachment
1488          *
1489          * @param string $body HTML code
1490          * @return string with removed images
1491          */
1492         private static function removePictures(string $body): string
1493         {
1494                 // Simplify image codes
1495                 $body = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '[img]$3[/img]', $body);
1496                 $body = preg_replace("/\[img\=(.*?)\](.*?)\[\/img\]/ism", '[img]$1[/img]', $body);
1497
1498                 // Now remove local links
1499                 $body = preg_replace_callback(
1500                         '/\[url=([^\[\]]*)\]\[img\](.*)\[\/img\]\[\/url\]/Usi',
1501                         function ($match) {
1502                                 // We remove the link when it is a link to a local photo page
1503                                 if (Photo::isLocalPage($match[1])) {
1504                                         return '';
1505                                 }
1506                                 // otherwise we just return the link
1507                                 return '[url]' . $match[1] . '[/url]';
1508                         },
1509                         $body
1510                 );
1511
1512                 // Remove all pictures
1513                 $body = preg_replace("/\[img\]([^\[\]]*)\[\/img\]/Usi", '', $body);
1514
1515                 return $body;
1516         }
1517
1518         /**
1519          * Fetches the "context" value for a givem item array from the "conversation" table
1520          *
1521          * @param array $item Item array
1522          * @return string with context url
1523          * @throws \Exception
1524          */
1525         private static function fetchContextURLForItem(array $item): string
1526         {
1527                 $conversation = DBA::selectFirst('conversation', ['conversation-href', 'conversation-uri'], ['item-uri' => $item['parent-uri']]);
1528                 if (DBA::isResult($conversation) && !empty($conversation['conversation-href'])) {
1529                         $context_uri = $conversation['conversation-href'];
1530                 } elseif (DBA::isResult($conversation) && !empty($conversation['conversation-uri'])) {
1531                         $context_uri = $conversation['conversation-uri'];
1532                 } else {
1533                         $context_uri = $item['parent-uri'] . '#context';
1534                 }
1535                 return $context_uri;
1536         }
1537
1538         /**
1539          * Returns if the post contains sensitive content ("nsfw")
1540          *
1541          * @param integer $uri_id URI id
1542          * @return boolean Whether URI id was found
1543          * @throws \Exception
1544          */
1545         private static function isSensitive(int $uri_id): bool
1546         {
1547                 return DBA::exists('tag-view', ['uri-id' => $uri_id, 'name' => 'nsfw', 'type' => Tag::HASHTAG]);
1548         }
1549
1550         /**
1551          * Creates event data
1552          *
1553          * @param array $item Item array
1554          * @return array with the event data
1555          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1556          */
1557         private static function createEvent(array $item): array
1558         {
1559                 $event = [];
1560                 $event['name'] = $item['event-summary'];
1561                 $event['content'] = BBCode::convertForUriId($item['uri-id'], $item['event-desc'], BBCode::ACTIVITYPUB);
1562                 $event['startTime'] = DateTimeFormat::utc($item['event-start'], 'c');
1563
1564                 if (!$item['event-nofinish']) {
1565                         $event['endTime'] = DateTimeFormat::utc($item['event-finish'], 'c');
1566                 }
1567
1568                 if (!empty($item['event-location'])) {
1569                         $item['location'] = $item['event-location'];
1570                         $event['location'] = self::createLocation($item);
1571                 }
1572
1573                 // 2021.12: Backward compatibility value, all the events now "adjust" to the viewer timezone
1574                 $event['dfrn:adjust'] = true;
1575
1576                 return $event;
1577         }
1578
1579         /**
1580          * Creates a note/article object array
1581          *
1582          * @param array $item
1583          * @return array with the object data
1584          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1585          * @throws \ImagickException
1586          */
1587         public static function createNote(array $item): array
1588         {
1589                 if (empty($item)) {
1590                         return [];
1591                 }
1592
1593                 // We are treating posts differently when they are directed to a community.
1594                 // This is done to better support Lemmy. Most of the changes should work with other systems as well.
1595                 // But to not risk compatibility issues we currently perform the changes only for communities.
1596                 if ($item['gravity'] == GRAVITY_PARENT) {
1597                         $isCommunityPost = !empty(Tag::getByURIId($item['uri-id'], [Tag::EXCLUSIVE_MENTION]));
1598                         $links = Post\Media::getByURIId($item['uri-id'], [Post\Media::HTML]);
1599                         if ($isCommunityPost && (count($links) == 1)) {
1600                                 $link = $links[0]['url'];
1601                         }
1602                 } else {
1603                         $isCommunityPost = false;
1604                 }
1605
1606                 if ($item['event-type'] == 'event') {
1607                         $type = 'Event';
1608                 } elseif (!empty($item['title'])) {
1609                         if (!$isCommunityPost || empty($link)) {
1610                                 $type = 'Article';
1611                         } else {
1612                                 // "Page" is used by Lemmy for posts that contain an external link
1613                                 $type = 'Page';
1614                         }
1615                 } else {
1616                         $type = 'Note';
1617                 }
1618
1619                 if ($item['deleted']) {
1620                         $type = 'Tombstone';
1621                 }
1622
1623                 $data = [];
1624                 $data['id'] = $item['uri'];
1625                 $data['type'] = $type;
1626
1627                 if ($item['deleted']) {
1628                         return $data;
1629                 }
1630
1631                 $data['summary'] = BBCode::toPlaintext(BBCode::getAbstract($item['body'], Protocol::ACTIVITYPUB));
1632
1633                 if ($item['uri'] != $item['thr-parent']) {
1634                         $data['inReplyTo'] = $item['thr-parent'];
1635                 } else {
1636                         $data['inReplyTo'] = null;
1637                 }
1638
1639                 $data['diaspora:guid'] = $item['guid'];
1640                 $data['published'] = DateTimeFormat::utc($item['created'] . '+00:00', DateTimeFormat::ATOM);
1641
1642                 if ($item['created'] != $item['edited']) {
1643                         $data['updated'] = DateTimeFormat::utc($item['edited'] . '+00:00', DateTimeFormat::ATOM);
1644                 }
1645
1646                 $data['url'] = $link ?? $item['plink'];
1647                 $data['attributedTo'] = $item['author-link'];
1648                 $data['sensitive'] = self::isSensitive($item['uri-id']);
1649                 $data['context'] = self::fetchContextURLForItem($item);
1650
1651                 if (!empty($item['title'])) {
1652                         $data['name'] = BBCode::toPlaintext($item['title'], false);
1653                 }
1654
1655                 $permission_block = self::createPermissionBlockForItem($item, false);
1656
1657                 $body = $item['body'];
1658
1659                 if ($type == 'Note') {
1660                         $body = $item['raw-body'] ?? self::removePictures($body);
1661                 }
1662
1663                 /**
1664                  * @todo Improve the automated summary
1665                  * This part is currently deactivated. The automated summary seems to be more
1666                  * confusing than helping. But possibly we will find a better way.
1667                  * So the code is left here for now as a reminder
1668                  *
1669                  * } elseif (($type == 'Article') && empty($data['summary'])) {
1670                  *              $regexp = "/[@!]\[url\=([^\[\]]*)\].*?\[\/url\]/ism";
1671                  *              $summary = preg_replace_callback($regexp, ['self', 'mentionAddrCallback'], $body);
1672                  *              $data['summary'] = BBCode::toPlaintext(Plaintext::shorten(self::removePictures($summary), 1000));
1673                  * }
1674                  */
1675
1676                 if (empty($item['uid']) || !Feature::isEnabled($item['uid'], 'explicit_mentions')) {
1677                         $body = self::prependMentions($body, $item['uri-id'], $item['author-link']);
1678                 }
1679
1680                 if ($type == 'Event') {
1681                         $data = array_merge($data, self::createEvent($item));
1682                 } else {
1683                         if ($isCommunityPost) {
1684                                 // For community posts we remove the visible "!user@domain.tld".
1685                                 // This improves the look at systems like Lemmy.
1686                                 // Also in the future we should control the community delivery via other methods.
1687                                 $body = preg_replace("/!\[url\=[^\[\]]*\][^\[\]]*\[\/url\]/ism", '', $body);
1688                         }
1689
1690                         if ($type == 'Page') {
1691                                 // When we transmit "Page" posts we have to remove the attachment.
1692                                 // The attachment contains the link that we already transmit in the "url" field.
1693                                 $body = preg_replace("/\s*\[attachment .*?\].*?\[\/attachment\]\s*/ism", '', $body);
1694                         }
1695
1696                         $body = BBCode::setMentionsToNicknames($body);
1697
1698                         $data['content'] = BBCode::convertForUriId($item['uri-id'], $body, BBCode::ACTIVITYPUB);
1699                 }
1700
1701                 // The regular "content" field does contain a minimized HTML. This is done since systems like
1702                 // Mastodon has got problems with - for example - embedded pictures.
1703                 // The contentMap does contain the unmodified HTML.
1704                 $language = self::getLanguage($item);
1705                 if (!empty($language)) {
1706                         $richbody = BBCode::setMentionsToNicknames($item['body'] ?? '');
1707                         $richbody = BBCode::removeAttachment($richbody);
1708
1709                         $data['contentMap'][$language] = BBCode::convertForUriId($item['uri-id'], $richbody, BBCode::EXTERNAL);
1710                 }
1711
1712                 $data['source'] = ['content' => $item['body'], 'mediaType' => "text/bbcode"];
1713
1714                 if (!empty($item['signed_text']) && ($item['uri'] != $item['thr-parent'])) {
1715                         $data['diaspora:comment'] = $item['signed_text'];
1716                 }
1717
1718                 $data['attachment'] = self::createAttachmentList($item, $type);
1719                 $data['tag'] = self::createTagList($item);
1720
1721                 if (empty($data['location']) && (!empty($item['coord']) || !empty($item['location']))) {
1722                         $data['location'] = self::createLocation($item);
1723                 }
1724
1725                 if (!empty($item['app'])) {
1726                         $data['generator'] = ['type' => 'Application', 'name' => $item['app']];
1727                 }
1728
1729                 $data = array_merge($data, $permission_block);
1730
1731                 return $data;
1732         }
1733
1734         /**
1735          * Fetches the language from the post, the user or the system.
1736          *
1737          * @param array $item
1738          * @return string language string
1739          */
1740         private static function getLanguage(array $item): string
1741         {
1742                 // Try to fetch the language from the post itself
1743                 if (!empty($item['language'])) {
1744                         $languages = array_keys(json_decode($item['language'], true));
1745                         if (!empty($languages[0])) {
1746                                 return $languages[0];
1747                         }
1748                 }
1749
1750                 // Otherwise use the user's language
1751                 if (!empty($item['uid'])) {
1752                         $user = DBA::selectFirst('user', ['language'], ['uid' => $item['uid']]);
1753                         if (!empty($user['language'])) {
1754                                 return $user['language'];
1755                         }
1756                 }
1757
1758                 // And finally just use the system language
1759                 return DI::config()->get('system', 'language');
1760         }
1761
1762         /**
1763          * Creates an an "add tag" entry
1764          *
1765          * @param array $item Item array
1766          * @param array $activity activity data
1767          * @return array with activity data for adding tags
1768          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1769          * @throws \ImagickException
1770          */
1771         private static function createAddTag(array $item, array $activity): array
1772         {
1773                 $object = XML::parseString($item['object']);
1774                 $target = XML::parseString($item['target']);
1775
1776                 $activity['diaspora:guid'] = $item['guid'];
1777                 $activity['actor'] = $item['author-link'];
1778                 $activity['target'] = (string)$target->id;
1779                 $activity['summary'] = BBCode::toPlaintext($item['body']);
1780                 $activity['object'] = ['id' => (string)$object->id, 'type' => 'tag', 'name' => (string)$object->title, 'content' => (string)$object->content];
1781
1782                 return $activity;
1783         }
1784
1785         /**
1786          * Creates an announce object entry
1787          *
1788          * @param array $item Item array
1789          * @param array $activity activity data
1790          * @return array with activity data
1791          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1792          * @throws \ImagickException
1793          */
1794         private static function createAnnounce(array $item, array $activity): array
1795         {
1796                 $orig_body = $item['body'];
1797                 $announce = self::getAnnounceArray($item);
1798                 if (empty($announce)) {
1799                         $activity['type'] = 'Create';
1800                         $activity['object'] = self::createNote($item);
1801                         return $activity;
1802                 }
1803
1804                 if (empty($announce['comment'])) {
1805                         // Pure announce, without a quote
1806                         $activity['type'] = 'Announce';
1807                         $activity['object'] = $announce['object']['uri'];
1808                         return $activity;
1809                 }
1810
1811                 // Quote
1812                 $activity['type'] = 'Create';
1813                 $item['body'] = $announce['comment'] . "\n" . $announce['object']['plink'];
1814                 $activity['object'] = self::createNote($item);
1815
1816                 /// @todo Finally descide how to implement this in AP. This is a possible way:
1817                 $activity['object']['attachment'][] = self::createNote($announce['object']);
1818
1819                 $activity['object']['source']['content'] = $orig_body;
1820                 return $activity;
1821         }
1822
1823         /**
1824          * Return announce related data if the item is an annunce
1825          *
1826          * @param array $item
1827          * @return array Announcement array
1828          */
1829         public static function getAnnounceArray(array $item): array
1830         {
1831                 $reshared = Item::getShareArray($item);
1832                 if (empty($reshared['guid'])) {
1833                         return [];
1834                 }
1835
1836                 $reshared_item = Post::selectFirst(Item::DELIVER_FIELDLIST, ['guid' => $reshared['guid']]);
1837                 if (!DBA::isResult($reshared_item)) {
1838                         return [];
1839                 }
1840
1841                 if (!in_array($reshared_item['network'], [Protocol::ACTIVITYPUB, Protocol::DFRN])) {
1842                         return [];
1843                 }
1844
1845                 $profile = APContact::getByURL($reshared_item['author-link'], false);
1846                 if (empty($profile)) {
1847                         return [];
1848                 }
1849
1850                 return ['object' => $reshared_item, 'actor' => $profile, 'comment' => $reshared['comment']];
1851         }
1852
1853         /**
1854          * Checks if the provided item array is an announce
1855          *
1856          * @param array $item Item array
1857          * @return boolean Whether item is an announcement
1858          */
1859         public static function isAnnounce(array $item): bool
1860         {
1861                 if (!empty($item['verb']) && ($item['verb'] == Activity::ANNOUNCE)) {
1862                         return true;
1863                 }
1864
1865                 $announce = self::getAnnounceArray($item);
1866                 if (empty($announce)) {
1867                         return false;
1868                 }
1869
1870                 return empty($announce['comment']);
1871         }
1872
1873         /**
1874          * Creates an activity id for a given contact id
1875          *
1876          * @param integer $cid Contact ID of target
1877          *
1878          * @return bool|string activity id
1879          */
1880         public static function activityIDFromContact(int $cid)
1881         {
1882                 $contact = DBA::selectFirst('contact', ['uid', 'id', 'created'], ['id' => $cid]);
1883                 if (!DBA::isResult($contact)) {
1884                         return false;
1885                 }
1886
1887                 $hash = hash('ripemd128', $contact['uid'].'-'.$contact['id'].'-'.$contact['created']);
1888                 $uuid = substr($hash, 0, 8). '-' . substr($hash, 8, 4) . '-' . substr($hash, 12, 4) . '-' . substr($hash, 16, 4) . '-' . substr($hash, 20, 12);
1889                 return DI::baseUrl() . '/activity/' . $uuid;
1890         }
1891
1892         /**
1893          * Transmits a contact suggestion to a given inbox
1894          *
1895          * @param integer $uid           User ID
1896          * @param string  $inbox         Target inbox
1897          * @param integer $suggestion_id Suggestion ID
1898          * @return boolean was the transmission successful?
1899          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1900          */
1901         public static function sendContactSuggestion(int $uid, string $inbox, int $suggestion_id): bool
1902         {
1903                 $owner = User::getOwnerDataById($uid);
1904
1905                 $suggestion = DI::fsuggest()->selectOneById($suggestion_id);
1906
1907                 $data = [
1908                         '@context' => ActivityPub::CONTEXT,
1909                         'id' => DI::baseUrl() . '/activity/' . System::createGUID(),
1910                         'type' => 'Announce',
1911                         'actor' => $owner['url'],
1912                         'object' => $suggestion->url,
1913                         'content' => $suggestion->note,
1914                         'instrument' => self::getService(),
1915                         'to' => [ActivityPub::PUBLIC_COLLECTION],
1916                         'cc' => []
1917                 ];
1918
1919                 $signed = LDSignature::sign($data, $owner);
1920
1921                 Logger::info('Deliver profile deletion for user ' . $uid . ' to ' . $inbox . ' via ActivityPub');
1922                 return HTTPSignature::transmit($signed, $inbox, $uid);
1923         }
1924
1925         /**
1926          * Transmits a profile relocation to a given inbox
1927          *
1928          * @param integer $uid   User ID
1929          * @param string  $inbox Target inbox
1930          * @return boolean was the transmission successful?
1931          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1932          */
1933         public static function sendProfileRelocation(int $uid, string $inbox): bool
1934         {
1935                 $owner = User::getOwnerDataById($uid);
1936
1937                 $data = [
1938                         '@context' => ActivityPub::CONTEXT,
1939                         'id' => DI::baseUrl() . '/activity/' . System::createGUID(),
1940                         'type' => 'dfrn:relocate',
1941                         'actor' => $owner['url'],
1942                         'object' => $owner['url'],
1943                         'published' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
1944                         'instrument' => self::getService(),
1945                         'to' => [ActivityPub::PUBLIC_COLLECTION],
1946                         'cc' => []
1947                 ];
1948
1949                 $signed = LDSignature::sign($data, $owner);
1950
1951                 Logger::info('Deliver profile relocation for user ' . $uid . ' to ' . $inbox . ' via ActivityPub');
1952                 return HTTPSignature::transmit($signed, $inbox, $uid);
1953         }
1954
1955         /**
1956          * Transmits a profile deletion to a given inbox
1957          *
1958          * @param integer $uid   User ID
1959          * @param string  $inbox Target inbox
1960          * @return boolean was the transmission successful?
1961          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1962          */
1963         public static function sendProfileDeletion(int $uid, string $inbox): bool
1964         {
1965                 $owner = User::getOwnerDataById($uid);
1966
1967                 if (empty($owner)) {
1968                         Logger::error('No owner data found, the deletion message cannot be processed.', ['user' => $uid]);
1969                         return false;
1970                 }
1971
1972                 if (empty($owner['uprvkey'])) {
1973                         Logger::error('No private key for owner found, the deletion message cannot be processed.', ['user' => $uid]);
1974                         return false;
1975                 }
1976
1977                 $data = ['@context' => ActivityPub::CONTEXT,
1978                         'id' => DI::baseUrl() . '/activity/' . System::createGUID(),
1979                         'type' => 'Delete',
1980                         'actor' => $owner['url'],
1981                         'object' => $owner['url'],
1982                         'published' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
1983                         'instrument' => self::getService(),
1984                         'to' => [ActivityPub::PUBLIC_COLLECTION],
1985                         'cc' => []];
1986
1987                 $signed = LDSignature::sign($data, $owner);
1988
1989                 Logger::info('Deliver profile deletion for user ' . $uid . ' to ' . $inbox . ' via ActivityPub');
1990                 return HTTPSignature::transmit($signed, $inbox, $uid);
1991         }
1992
1993         /**
1994          * Transmits a profile change to a given inbox
1995          *
1996          * @param integer $uid   User ID
1997          * @param string  $inbox Target inbox
1998          * @return boolean was the transmission successful?
1999          * @throws HTTPException\InternalServerErrorException
2000          * @throws HTTPException\NotFoundException
2001          * @throws \ImagickException
2002          */
2003         public static function sendProfileUpdate(int $uid, string $inbox): bool
2004         {
2005                 $owner = User::getOwnerDataById($uid);
2006                 $profile = APContact::getByURL($owner['url']);
2007
2008                 $data = ['@context' => ActivityPub::CONTEXT,
2009                         'id' => DI::baseUrl() . '/activity/' . System::createGUID(),
2010                         'type' => 'Update',
2011                         'actor' => $owner['url'],
2012                         'object' => self::getProfile($uid),
2013                         'published' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
2014                         'instrument' => self::getService(),
2015                         'to' => [$profile['followers']],
2016                         'cc' => []];
2017
2018                 $signed = LDSignature::sign($data, $owner);
2019
2020                 Logger::info('Deliver profile update for user ' . $uid . ' to ' . $inbox . ' via ActivityPub');
2021                 return HTTPSignature::transmit($signed, $inbox, $uid);
2022         }
2023
2024         /**
2025          * Transmits a given activity to a target
2026          *
2027          * @param string  $activity Type name
2028          * @param string  $target   Target profile
2029          * @param integer $uid      User ID
2030          * @param string  $id Activity-identifier
2031          * @return bool
2032          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2033          * @throws \ImagickException
2034          * @throws \Exception
2035          */
2036         public static function sendActivity(string $activity, string $target, int $uid, string $id = ''): bool
2037         {
2038                 $profile = APContact::getByURL($target);
2039                 if (empty($profile['inbox'])) {
2040                         Logger::warning('No inbox found for target', ['target' => $target, 'profile' => $profile]);
2041                         return false;
2042                 }
2043
2044                 $owner = User::getOwnerDataById($uid);
2045
2046                 if (empty($id)) {
2047                         $id = DI::baseUrl() . '/activity/' . System::createGUID();
2048                 }
2049
2050                 $data = [
2051                         '@context' => ActivityPub::CONTEXT,
2052                         'id' => $id,
2053                         'type' => $activity,
2054                         'actor' => $owner['url'],
2055                         'object' => $profile['url'],
2056                         'instrument' => self::getService(),
2057                         'to' => [$profile['url']],
2058                 ];
2059
2060                 Logger::info('Sending activity ' . $activity . ' to ' . $target . ' for user ' . $uid);
2061
2062                 $signed = LDSignature::sign($data, $owner);
2063                 return HTTPSignature::transmit($signed, $profile['inbox'], $uid);
2064         }
2065
2066         /**
2067          * Transmits a "follow object" activity to a target
2068          * This is a preparation for sending automated "follow" requests when receiving "Announce" messages
2069          *
2070          * @param string  $object Object URL
2071          * @param string  $target Target profile
2072          * @param integer $uid    User ID
2073          * @return bool
2074          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2075          * @throws \ImagickException
2076          * @throws \Exception
2077          */
2078         public static function sendFollowObject(string $object, string $target, int $uid = 0): bool
2079         {
2080                 $profile = APContact::getByURL($target);
2081                 if (empty($profile['inbox'])) {
2082                         Logger::warning('No inbox found for target', ['target' => $target, 'profile' => $profile]);
2083                         return false;
2084                 }
2085
2086                 if (empty($uid)) {
2087                         // Fetch the list of administrators
2088                         $admin_mail = explode(',', str_replace(' ', '', DI::config()->get('config', 'admin_email')));
2089
2090                         // We need to use some user as a sender. It doesn't care who it will send. We will use an administrator account.
2091                         $condition = ['verified' => true, 'blocked' => false, 'account_removed' => false, 'account_expired' => false, 'email' => $admin_mail];
2092                         $first_user = DBA::selectFirst('user', ['uid'], $condition);
2093                         $uid = $first_user['uid'];
2094                 }
2095
2096                 $condition = ['verb' => Activity::FOLLOW, 'uid' => 0, 'parent-uri' => $object,
2097                         'author-id' => Contact::getPublicIdByUserId($uid)];
2098                 if (Post::exists($condition)) {
2099                         Logger::info('Follow for ' . $object . ' for user ' . $uid . ' does already exist.');
2100                         return false;
2101                 }
2102
2103                 $owner = User::getOwnerDataById($uid);
2104
2105                 $data = [
2106                         '@context' => ActivityPub::CONTEXT,
2107                         'id' => DI::baseUrl() . '/activity/' . System::createGUID(),
2108                         'type' => 'Follow',
2109                         'actor' => $owner['url'],
2110                         'object' => $object,
2111                         'instrument' => self::getService(),
2112                         'to' => [$profile['url']],
2113                 ];
2114
2115                 Logger::info('Sending follow ' . $object . ' to ' . $target . ' for user ' . $uid);
2116
2117                 $signed = LDSignature::sign($data, $owner);
2118                 return HTTPSignature::transmit($signed, $profile['inbox'], $uid);
2119         }
2120
2121         /**
2122          * Transmit a message that the contact request had been accepted
2123          *
2124          * @param string  $target Target profile
2125          * @param string  $id Object id
2126          * @param integer $uid    User ID
2127          * @return void
2128          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2129          * @throws \ImagickException
2130          */
2131         public static function sendContactAccept(string $target, string $id, int $uid)
2132         {
2133                 $profile = APContact::getByURL($target);
2134                 if (empty($profile['inbox'])) {
2135                         Logger::warning('No inbox found for target', ['target' => $target, 'profile' => $profile]);
2136                         return;
2137                 }
2138
2139                 $owner = User::getOwnerDataById($uid);
2140                 $data = [
2141                         '@context' => ActivityPub::CONTEXT,
2142                         'id' => DI::baseUrl() . '/activity/' . System::createGUID(),
2143                         'type' => 'Accept',
2144                         'actor' => $owner['url'],
2145                         'object' => [
2146                                 'id' => $id,
2147                                 'type' => 'Follow',
2148                                 'actor' => $profile['url'],
2149                                 'object' => $owner['url']
2150                         ],
2151                         'instrument' => self::getService(),
2152                         'to' => [$profile['url']],
2153                 ];
2154
2155                 Logger::debug('Sending accept to ' . $target . ' for user ' . $uid . ' with id ' . $id);
2156
2157                 $signed = LDSignature::sign($data, $owner);
2158                 HTTPSignature::transmit($signed, $profile['inbox'], $uid);
2159         }
2160
2161         /**
2162          * Reject a contact request or terminates the contact relation
2163          *
2164          * @param string $target   Target profile
2165          * @param string $objectId Object id
2166          * @param int    $uid      User ID
2167          * @return bool Operation success
2168          * @throws HTTPException\InternalServerErrorException
2169          * @throws \ImagickException
2170          */
2171         public static function sendContactReject(string $target, string $objectId, int $uid): bool
2172         {
2173                 $profile = APContact::getByURL($target);
2174                 if (empty($profile['inbox'])) {
2175                         Logger::warning('No inbox found for target', ['target' => $target, 'profile' => $profile]);
2176                         return false;
2177                 }
2178
2179                 $owner = User::getOwnerDataById($uid);
2180                 $data = [
2181                         '@context' => ActivityPub::CONTEXT,
2182                         'id' => DI::baseUrl() . '/activity/' . System::createGUID(),
2183                         'type' => 'Reject',
2184                         'actor'  => $owner['url'],
2185                         'object' => [
2186                                 'id' => $objectId,
2187                                 'type' => 'Follow',
2188                                 'actor' => $profile['url'],
2189                                 'object' => $owner['url']
2190                         ],
2191                         'instrument' => self::getService(),
2192                         'to' => [$profile['url']],
2193                 ];
2194
2195                 Logger::debug('Sending reject to ' . $target . ' for user ' . $uid . ' with id ' . $objectId);
2196
2197                 $signed = LDSignature::sign($data, $owner);
2198                 return HTTPSignature::transmit($signed, $profile['inbox'], $uid);
2199         }
2200
2201         /**
2202          * Transmits a message that we don't want to follow this contact anymore
2203          *
2204          * @param string  $target Target profile
2205          * @param integer $cid    Contact id
2206          * @param integer $uid    User ID
2207          * @return bool success
2208          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2209          * @throws \ImagickException
2210          * @throws \Exception
2211          */
2212         public static function sendContactUndo(string $target, int $cid, int $uid): bool
2213         {
2214                 $profile = APContact::getByURL($target);
2215                 if (empty($profile['inbox'])) {
2216                         Logger::warning('No inbox found for target', ['target' => $target, 'profile' => $profile]);
2217                         return false;
2218                 }
2219
2220                 $object_id = self::activityIDFromContact($cid);
2221                 if (empty($object_id)) {
2222                         return false;
2223                 }
2224
2225                 $objectId = DI::baseUrl() . '/activity/' . System::createGUID();
2226
2227                 $owner = User::getOwnerDataById($uid);
2228                 $data = [
2229                         '@context' => ActivityPub::CONTEXT,
2230                         'id' => $objectId,
2231                         'type' => 'Undo',
2232                         'actor' => $owner['url'],
2233                         'object' => [
2234                                 'id' => $object_id,
2235                                 'type' => 'Follow',
2236                                 'actor' => $owner['url'],
2237                                 'object' => $profile['url']
2238                         ],
2239                         'instrument' => self::getService(),
2240                         'to' => [$profile['url']],
2241                 ];
2242
2243                 Logger::info('Sending undo to ' . $target . ' for user ' . $uid . ' with id ' . $objectId);
2244
2245                 $signed = LDSignature::sign($data, $owner);
2246                 return HTTPSignature::transmit($signed, $profile['inbox'], $uid);
2247         }
2248
2249         /**
2250          * Prepends mentions (@) to $body variable
2251          *
2252          * @param string $body HTML code
2253          * @param int    $uriId
2254          * @param string $authorLink Author link
2255          * @return string HTML code with prepended mentions
2256          */
2257         private static function prependMentions(string $body, int $uriid, string $authorLink): string
2258         {
2259                 $mentions = [];
2260
2261                 foreach (Tag::getByURIId($uriid, [Tag::IMPLICIT_MENTION]) as $tag) {
2262                         $profile = Contact::getByURL($tag['url'], false, ['addr', 'contact-type', 'nick']);
2263                         if (!empty($profile['addr'])
2264                                 && $profile['contact-type'] != Contact::TYPE_COMMUNITY
2265                                 && !strstr($body, $profile['addr'])
2266                                 && !strstr($body, $tag['url'])
2267                                 && $tag['url'] !== $authorLink
2268                         ) {
2269                                 $mentions[] = '@[url=' . $tag['url'] . ']' . $profile['nick'] . '[/url]';
2270                         }
2271                 }
2272
2273                 $mentions[] = $body;
2274
2275                 return implode(' ', $mentions);
2276         }
2277 }