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