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