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