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