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