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