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