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