]> git.mxchange.org Git - friendica.git/blob - src/Protocol/ActivityPub/Transmitter.php
Relay posts with the original protocol
[friendica.git] / src / Protocol / ActivityPub / Transmitter.php
1 <?php
2 /**
3  * @copyright Copyright (C) 2020, Friendica
4  *
5  * @license GNU AGPL version 3 or any later version
6  *
7  * This program is free software: you can redistribute it and/or modify
8  * it under the terms of the GNU Affero General Public License as
9  * published by the Free Software Foundation, either version 3 of the
10  * License, or (at your option) any later version.
11  *
12  * This program is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15  * GNU Affero General Public License for more details.
16  *
17  * You should have received a copy of the GNU Affero General Public License
18  * along with this program.  If not, see <https://www.gnu.org/licenses/>.
19  *
20  */
21
22 namespace Friendica\Protocol\ActivityPub;
23
24 use Friendica\Content\Feature;
25 use Friendica\Content\Text\BBCode;
26 use Friendica\Content\Text\Plaintext;
27 use Friendica\Core\Cache\Duration;
28 use Friendica\Core\Logger;
29 use Friendica\Core\Protocol;
30 use Friendica\Core\System;
31 use Friendica\Database\DBA;
32 use Friendica\DI;
33 use Friendica\Model\APContact;
34 use Friendica\Model\Contact;
35 use Friendica\Model\Conversation;
36 use Friendica\Model\Item;
37 use Friendica\Model\ItemURI;
38 use Friendica\Model\Profile;
39 use Friendica\Model\Photo;
40 use Friendica\Model\Post;
41 use Friendica\Model\Tag;
42 use Friendica\Model\User;
43 use Friendica\Protocol\Activity;
44 use Friendica\Protocol\ActivityPub;
45 use Friendica\Protocol\Relay;
46 use Friendica\Util\DateTimeFormat;
47 use Friendica\Util\HTTPSignature;
48 use Friendica\Util\JsonLD;
49 use Friendica\Util\LDSignature;
50 use Friendica\Util\Map;
51 use Friendica\Util\Network;
52 use Friendica\Util\XML;
53
54 require_once 'include/api.php';
55 require_once 'mod/share.php';
56
57 /**
58  * ActivityPub Transmitter Protocol class
59  *
60  * To-Do:
61  * @todo Undo Announce
62  */
63 class Transmitter
64 {
65         /**
66          * Add relay servers to the list of inboxes
67          *
68          * @param array $inboxes
69          * @return array inboxes with added relay servers
70          */
71         public static function addRelayServerInboxes(array $inboxes = [])
72         {
73                 $contacts = DBA::select('apcontact', ['inbox'],
74                         ["`type` = ? AND `url` IN (SELECT `url` FROM `contact` WHERE `uid` = ? AND `rel` IN (?, ?))",
75                                 'Application', 0, Contact::FOLLOWER, Contact::FRIEND]);
76                 while ($contact = DBA::fetch($contacts)) {
77                         $inboxes[] = $contact['inbox'];
78                 }
79                 DBA::close($contacts);
80
81                 return $inboxes;
82         }
83
84         /**
85          * Add relay servers to the list of inboxes
86          *
87          * @param array $inboxes
88          * @return array inboxes with added relay servers
89          */
90         public static function addRelayServerInboxesForItem(int $item_id, array $inboxes = [])
91         {
92                 $relays = Relay::getList($item_id, [], [Protocol::ACTIVITYPUB]);
93                 if (empty($relays)) {
94                         return $inboxes;
95                 }
96
97                 foreach ($relays as $relay) {
98                         if (!in_array($relay['batch'], $inboxes)) {
99                                 $inboxes[] = $relay['batch'];
100                         }
101                 }
102                 return $inboxes;
103         }
104
105         /**
106          * Subscribe to a relay
107          *
108          * @param string $url Subscribe actor url
109          * @return bool success
110          */
111         public static function sendRelayFollow(string $url)
112         {
113                 $contact = Contact::getByURL($url);
114                 if (empty($contact)) {
115                         return false;
116                 }
117
118                 $activity_id = ActivityPub\Transmitter::activityIDFromContact($contact['id']);
119                 $success = ActivityPub\Transmitter::sendActivity('Follow', $url, 0, $activity_id);
120                 if ($success) {
121                         $rel = $contact['rel'] == Contact::SHARING ? Contact::FRIEND : Contact::FOLLOWER;
122                         DBA::update('contact', ['rel' => $rel], ['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                         $rel = $contact['rel'] == Contact::FRIEND ? Contact::SHARING : Contact::NOTHING;
145                         DBA::update('contact', ['rel' => $rel], ['id' => $contact['id']]);
146                 }
147
148                 return $success;
149         }
150         
151         /**
152          * Collects a list of contacts of the given owner
153          *
154          * @param array     $owner  Owner array
155          * @param int|array $rel    The relevant value(s) contact.rel should match
156          * @param string    $module The name of the relevant AP endpoint module (followers|following)
157          * @param integer   $page   Page number
158          *
159          * @return array of owners
160          * @throws \Exception
161          */
162         public static function getContacts($owner, $rel, $module, $page = null)
163         {
164                 $parameters = [
165                         'rel' => $rel,
166                         'uid' => $owner['uid'],
167                         'self' => false,
168                         'deleted' => false,
169                         'hidden' => false,
170                         'archive' => false,
171                         'pending' => false,
172                         'blocked' => false,
173                 ];
174                 $condition = DBA::buildCondition($parameters);
175
176                 $sql = "SELECT COUNT(*) as `count`
177                         FROM `contact`
178                         JOIN `apcontact` ON `apcontact`.`url` = `contact`.`url`
179                         " . $condition;
180
181                 $contacts = DBA::fetchFirst($sql, ...$parameters);
182
183                 $modulePath = '/' . $module . '/';
184
185                 $data = ['@context' => ActivityPub::CONTEXT];
186                 $data['id'] = DI::baseUrl() . $modulePath . $owner['nickname'];
187                 $data['type'] = 'OrderedCollection';
188                 $data['totalItems'] = $contacts['count'];
189
190                 // When we hide our friends we will only show the pure number but don't allow more.
191                 $profile = Profile::getByUID($owner['uid']);
192                 if (!empty($profile['hide-friends'])) {
193                         return $data;
194                 }
195
196                 if (empty($page)) {
197                         $data['first'] = DI::baseUrl() . $modulePath . $owner['nickname'] . '?page=1';
198                 } else {
199                         $data['type'] = 'OrderedCollectionPage';
200                         $list = [];
201
202                         $sql = "SELECT `contact`.`url`
203                                 FROM `contact`
204                                 JOIN `apcontact` ON `apcontact`.`url` = `contact`.`url`
205                                 " . $condition . "
206                                 LIMIT ?, ?";
207
208                         $parameters[] = ($page - 1) * 100;
209                         $parameters[] = 100;
210
211                         $contacts = DBA::p($sql, ...$parameters);
212                         while ($contact = DBA::fetch($contacts)) {
213                                 $list[] = $contact['url'];
214                         }
215                         DBA::close($contacts);
216
217                         if (!empty($list)) {
218                                 $data['next'] = DI::baseUrl() . $modulePath . $owner['nickname'] . '?page=' . ($page + 1);
219                         }
220
221                         $data['partOf'] = DI::baseUrl() . $modulePath . $owner['nickname'];
222
223                         $data['orderedItems'] = $list;
224                 }
225
226                 return $data;
227         }
228
229         /**
230          * Public posts for the given owner
231          *
232          * @param array   $owner     Owner array
233          * @param integer $page      Page number
234          * @param string  $requester URL of requesting account
235          *
236          * @return array of posts
237          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
238          * @throws \ImagickException
239          */
240         public static function getOutbox($owner, $page = null, $requester = '')
241         {
242                 $public_contact = Contact::getIdForURL($owner['url']);
243                 $condition = ['uid' => 0, 'contact-id' => $public_contact,
244                         'private' => [Item::PUBLIC, Item::UNLISTED]];
245
246                 if (!empty($requester)) {
247                         $requester_id = Contact::getIdForURL($requester, $owner['uid']);
248                         if (!empty($requester_id)) {
249                                 $permissionSets = DI::permissionSet()->selectByContactId($requester_id, $owner['uid']);
250                                 if (!empty($permissionSets)) {
251                                         $condition = ['uid' => $owner['uid'], 'origin' => true,
252                                                 'psid' => array_merge($permissionSets->column('id'),
253                                                         [DI::permissionSet()->getIdFromACL($owner['uid'], '', '', '', '')])];
254                                 }
255                         }
256                 }
257
258                 $condition = array_merge($condition,
259                         ['author-id' => $public_contact,
260                         'gravity' => [GRAVITY_PARENT, GRAVITY_COMMENT],
261                         'deleted' => false, 'visible' => true, 'moderated' => false]);
262
263                 $count = DBA::count('item', $condition);
264
265                 $data = ['@context' => ActivityPub::CONTEXT];
266                 $data['id'] = DI::baseUrl() . '/outbox/' . $owner['nickname'];
267                 $data['type'] = 'OrderedCollection';
268                 $data['totalItems'] = $count;
269
270                 if (empty($page)) {
271                         $data['first'] = DI::baseUrl() . '/outbox/' . $owner['nickname'] . '?page=1';
272                 } else {
273                         $data['type'] = 'OrderedCollectionPage';
274                         $list = [];
275
276                         $condition['parent-network'] = Protocol::NATIVE_SUPPORT;
277
278                         $items = Item::select(['id'], $condition, ['limit' => [($page - 1) * 20, 20], 'order' => ['created' => true]]);
279                         while ($item = Item::fetch($items)) {
280                                 $activity = self::createActivityFromItem($item['id'], true);
281                                 $activity['type'] = $activity['type'] == 'Update' ? 'Create' : $activity['type'];
282
283                                 // Only list "Create" activity objects here, no reshares
284                                 if (!empty($activity['object']) && ($activity['type'] == 'Create')) {
285                                         $list[] = $activity['object'];
286                                 }
287                         }
288
289                         if (!empty($list)) {
290                                 $data['next'] = DI::baseUrl() . '/outbox/' . $owner['nickname'] . '?page=' . ($page + 1);
291                         }
292
293                         $data['partOf'] = DI::baseUrl() . '/outbox/' . $owner['nickname'];
294
295                         $data['orderedItems'] = $list;
296                 }
297
298                 return $data;
299         }
300
301         /**
302          * Return the service array containing information the used software and it's url
303          *
304          * @return array with service data
305          */
306         private static function getService()
307         {
308                 return ['type' => 'Service',
309                         'name' =>  FRIENDICA_PLATFORM . " '" . FRIENDICA_CODENAME . "' " . FRIENDICA_VERSION . '-' . DB_UPDATE_VERSION,
310                         'url' => DI::baseUrl()->get()];
311         }
312
313         /**
314          * Return the ActivityPub profile of the given user
315          *
316          * @param integer $uid User ID
317          * @return array with profile data
318          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
319          */
320         public static function getProfile($uid)
321         {
322                 if ($uid != 0) {
323                         $condition = ['uid' => $uid, 'blocked' => false, 'account_expired' => false,
324                                 'account_removed' => false, 'verified' => true];
325                         $fields = ['guid', 'nickname', 'pubkey', 'account-type', 'page-flags'];
326                         $user = DBA::selectFirst('user', $fields, $condition);
327                         if (!DBA::isResult($user)) {
328                                 return [];
329                         }
330
331                         $fields = ['locality', 'region', 'country-name'];
332                         $profile = DBA::selectFirst('profile', $fields, ['uid' => $uid]);
333                         if (!DBA::isResult($profile)) {
334                                 return [];
335                         }
336
337                         $fields = ['name', 'url', 'location', 'about', 'avatar', 'photo'];
338                         $contact = DBA::selectFirst('contact', $fields, ['uid' => $uid, 'self' => true]);
339                         if (!DBA::isResult($contact)) {
340                                 return [];
341                         }
342                 } else {
343                         $contact = User::getSystemAccount();
344                         $user = ['guid' => '', 'nickname' => $contact['nick'], 'pubkey' => $contact['pubkey'],
345                                 'account-type' => $contact['contact-type'], 'page-flags' => User::PAGE_FLAGS_NORMAL];
346                         $profile = ['locality' => '', 'region' => '', 'country-name' => ''];
347                 }
348
349                 $data = ['@context' => ActivityPub::CONTEXT];
350                 $data['id'] = $contact['url'];
351
352                 if (!empty($user['guid'])) {
353                         $data['diaspora:guid'] = $user['guid'];
354                 }
355
356                 $data['type'] = ActivityPub::ACCOUNT_TYPES[$user['account-type']];
357                 
358                 if ($uid != 0) {
359                         $data['following'] = DI::baseUrl() . '/following/' . $user['nickname'];
360                         $data['followers'] = DI::baseUrl() . '/followers/' . $user['nickname'];
361                         $data['inbox'] = DI::baseUrl() . '/inbox/' . $user['nickname'];
362                         $data['outbox'] = DI::baseUrl() . '/outbox/' . $user['nickname'];
363                 } else {
364                         $data['inbox'] = DI::baseUrl() . '/friendica/inbox';
365                 }
366
367                 $data['preferredUsername'] = $user['nickname'];
368                 $data['name'] = $contact['name'];
369
370                 if (!empty($profile['country-name'] . $profile['region'] . $profile['locality'])) {
371                         $data['vcard:hasAddress'] = ['@type' => 'vcard:Home', 'vcard:country-name' => $profile['country-name'],
372                                 'vcard:region' => $profile['region'], 'vcard:locality' => $profile['locality']];
373                 }
374
375                 if (!empty($contact['about'])) {
376                         $data['summary'] = BBCode::convert($contact['about'], false);
377                 }
378
379                 $data['url'] = $contact['url'];
380                 $data['manuallyApprovesFollowers'] = in_array($user['page-flags'], [User::PAGE_FLAGS_NORMAL, User::PAGE_FLAGS_PRVGROUP]);
381                 $data['publicKey'] = ['id' => $contact['url'] . '#main-key',
382                         'owner' => $contact['url'],
383                         'publicKeyPem' => $user['pubkey']];
384                 $data['endpoints'] = ['sharedInbox' => DI::baseUrl() . '/inbox'];
385                 $data['icon'] = ['type' => 'Image',
386                         'url' => $contact['photo']];
387
388                 $data['generator'] = self::getService();
389
390                 // tags: https://kitty.town/@inmysocks/100656097926961126.json
391                 return $data;
392         }
393
394         /**
395          * @param string $username
396          * @return array
397          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
398          */
399         public static function getDeletedUser($username)
400         {
401                 return [
402                         '@context' => ActivityPub::CONTEXT,
403                         'id' => DI::baseUrl() . '/profile/' . $username,
404                         'type' => 'Tombstone',
405                         'published' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
406                         'updated' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
407                         'deleted' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
408                 ];
409         }
410
411         /**
412          * Returns an array with permissions of a given item array
413          *
414          * @param array $item
415          *
416          * @return array with permissions
417          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
418          * @throws \ImagickException
419          */
420         private static function fetchPermissionBlockFromConversation($item)
421         {
422                 if (empty($item['thr-parent'])) {
423                         return [];
424                 }
425
426                 $condition = ['item-uri' => $item['thr-parent'], 'protocol' => Conversation::PARCEL_ACTIVITYPUB];
427                 $conversation = DBA::selectFirst('conversation', ['source'], $condition);
428                 if (!DBA::isResult($conversation)) {
429                         return [];
430                 }
431
432                 $activity = json_decode($conversation['source'], true);
433
434                 $actor = JsonLD::fetchElement($activity, 'actor', 'id');
435                 if (!empty($actor)) {
436                         $permissions['to'][] = $actor;
437                         $profile = APContact::getByURL($actor);
438                 } else {
439                         $profile = [];
440                 }
441
442                 $item_profile = APContact::getByURL($item['author-link']);
443                 $exclude[] = $item['author-link'];
444
445                 if ($item['gravity'] == GRAVITY_PARENT) {
446                         $exclude[] = $item['owner-link'];
447                 }
448
449                 foreach (['to', 'cc', 'bto', 'bcc'] as $element) {
450                         if (empty($activity[$element])) {
451                                 continue;
452                         }
453                         if (is_string($activity[$element])) {
454                                 $activity[$element] = [$activity[$element]];
455                         }
456
457                         foreach ($activity[$element] as $receiver) {
458                                 if (empty($receiver)) {
459                                         continue;
460                                 }
461
462                                 if (!empty($profile['followers']) && $receiver == $profile['followers'] && !empty($item_profile['followers'])) {
463                                         $permissions[$element][] = $item_profile['followers'];
464                                 } elseif (!in_array($receiver, $exclude)) {
465                                         $permissions[$element][] = $receiver;
466                                 }
467                         }
468                 }
469                 return $permissions;
470         }
471
472         /**
473          * Check if the given item id is from ActivityPub
474          *
475          * @param integer $item_id
476          * @return boolean "true" if the post is from ActivityPub
477          */
478         private static function isAPPost(int $item_id) {
479                 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', ['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] = $target;
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                                                 if (empty($profile['sharedinbox']) || $personal || $blindcopy) {
820                                                         $target = $profile['inbox'];
821                                                 } else {
822                                                         $target = $profile['sharedinbox'];
823                                                 }
824                                                 if (!self::archivedInbox($target)) {
825                                                         $inboxes[$target] = $target;
826                                                 }
827                                         }
828                                 }
829                         }
830                 }
831
832                 return $inboxes;
833         }
834
835         /**
836          * Creates an array in the structure of the item table for a given mail id
837          *
838          * @param integer $mail_id
839          *
840          * @return array
841          * @throws \Exception
842          */
843         public static function ItemArrayFromMail($mail_id)
844         {
845                 $mail = DBA::selectFirst('mail', [], ['id' => $mail_id]);
846                 if (!DBA::isResult($mail)) {
847                         return [];
848                 }
849
850                 $mail['uri-id'] = ItemURI::insert(['uri' => $mail['uri'], 'guid' => $mail['guid']]);
851
852                 $reply = DBA::selectFirst('mail', ['uri'], ['parent-uri' => $mail['parent-uri'], 'reply' => false]);
853
854                 // Making the post more compatible for Mastodon by:
855                 // - Making it a note and not an article (no title)
856                 // - Moving the title into the "summary" field that is used as a "content warning"
857                 $mail['body'] = '[abstract]' . $mail['title'] . "[/abstract]\n" . $mail['body'];
858                 $mail['title'] = '';
859
860                 $mail['author-link'] = $mail['owner-link'] = $mail['from-url'];
861                 $mail['allow_cid'] = '<'.$mail['contact-id'].'>';
862                 $mail['allow_gid'] = '';
863                 $mail['deny_cid'] = '';
864                 $mail['deny_gid'] = '';
865                 $mail['private'] = true;
866                 $mail['deleted'] = false;
867                 $mail['edited'] = $mail['created'];
868                 $mail['plink'] = $mail['uri'];
869                 $mail['thr-parent'] = $reply['uri'];
870                 $mail['gravity'] = ($mail['reply'] ? GRAVITY_COMMENT: GRAVITY_PARENT);
871
872                 $mail['event-type'] = '';
873
874                 $mail['parent'] = 0;
875
876                 return $mail;
877         }
878
879         /**
880          * Creates an activity array for a given mail id
881          *
882          * @param integer $mail_id
883          * @param boolean $object_mode Is the activity item is used inside another object?
884          *
885          * @return array of activity
886          * @throws \Exception
887          */
888         public static function createActivityFromMail($mail_id, $object_mode = false)
889         {
890                 $mail = self::ItemArrayFromMail($mail_id);
891                 if (empty($mail)) {
892                         return [];
893                 }
894                 $object = self::createNote($mail);
895
896                 if (!$object_mode) {
897                         $data = ['@context' => ActivityPub::CONTEXT];
898                 } else {
899                         $data = [];
900                 }
901
902                 $data['id'] = $mail['uri'] . '/Create';
903                 $data['type'] = 'Create';
904                 $data['actor'] = $mail['author-link'];
905                 $data['published'] = DateTimeFormat::utc($mail['created'] . '+00:00', DateTimeFormat::ATOM);
906                 $data['instrument'] = self::getService();
907                 $data = array_merge($data, self::createPermissionBlockForItem($mail, true));
908
909                 if (empty($data['to']) && !empty($data['cc'])) {
910                         $data['to'] = $data['cc'];
911                 }
912
913                 if (empty($data['to']) && !empty($data['bcc'])) {
914                         $data['to'] = $data['bcc'];
915                 }
916
917                 unset($data['cc']);
918                 unset($data['bcc']);
919
920                 $object['to'] = $data['to'];
921                 $object['tag'] = [['type' => 'Mention', 'href' => $object['to'][0], 'name' => '']];
922
923                 unset($object['cc']);
924                 unset($object['bcc']);
925
926                 $data['directMessage'] = true;
927
928                 $data['object'] = $object;
929
930                 $owner = User::getOwnerDataById($mail['uid']);
931
932                 if (!$object_mode && !empty($owner)) {
933                         return LDSignature::sign($data, $owner);
934                 } else {
935                         return $data;
936                 }
937         }
938
939         /**
940          * Returns the activity type of a given item
941          *
942          * @param array $item
943          *
944          * @return string with activity type
945          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
946          * @throws \ImagickException
947          */
948         private static function getTypeOfItem($item)
949         {
950                 $reshared = false;
951
952                 // Only check for a reshare, if it is a real reshare and no quoted reshare
953                 if (strpos($item['body'], "[share") === 0) {
954                         $announce = self::getAnnounceArray($item);
955                         $reshared = !empty($announce);
956                 }
957
958                 if ($reshared) {
959                         $type = 'Announce';
960                 } elseif ($item['verb'] == Activity::POST) {
961                         if ($item['created'] == $item['edited']) {
962                                 $type = 'Create';
963                         } else {
964                                 $type = 'Update';
965                         }
966                 } elseif ($item['verb'] == Activity::LIKE) {
967                         $type = 'Like';
968                 } elseif ($item['verb'] == Activity::DISLIKE) {
969                         $type = 'Dislike';
970                 } elseif ($item['verb'] == Activity::ATTEND) {
971                         $type = 'Accept';
972                 } elseif ($item['verb'] == Activity::ATTENDNO) {
973                         $type = 'Reject';
974                 } elseif ($item['verb'] == Activity::ATTENDMAYBE) {
975                         $type = 'TentativeAccept';
976                 } elseif ($item['verb'] == Activity::FOLLOW) {
977                         $type = 'Follow';
978                 } elseif ($item['verb'] == Activity::TAG) {
979                         $type = 'Add';
980                 } elseif ($item['verb'] == Activity::ANNOUNCE) {
981                         $type = 'Announce';
982                 } else {
983                         $type = '';
984                 }
985
986                 return $type;
987         }
988
989         /**
990          * Creates the activity or fetches it from the cache
991          *
992          * @param integer $item_id
993          * @param boolean $force Force new cache entry
994          *
995          * @return array with the activity
996          * @throws \Exception
997          */
998         public static function createCachedActivityFromItem($item_id, $force = false)
999         {
1000                 $cachekey = 'APDelivery:createActivity:' . $item_id;
1001
1002                 if (!$force) {
1003                         $data = DI::cache()->get($cachekey);
1004                         if (!is_null($data)) {
1005                                 return $data;
1006                         }
1007                 }
1008
1009                 $data = self::createActivityFromItem($item_id);
1010
1011                 DI::cache()->set($cachekey, $data, Duration::QUARTER_HOUR);
1012                 return $data;
1013         }
1014
1015         /**
1016          * Creates an activity array for a given item id
1017          *
1018          * @param integer $item_id
1019          * @param boolean $object_mode Is the activity item is used inside another object?
1020          *
1021          * @return false|array
1022          * @throws \Exception
1023          */
1024         public static function createActivityFromItem(int $item_id, bool $object_mode = false)
1025         {
1026                 Logger::info('Fetching activity', ['item' => $item_id]);
1027                 $item = Item::selectFirst([], ['id' => $item_id, 'parent-network' => Protocol::NATIVE_SUPPORT]);
1028                 if (!DBA::isResult($item)) {
1029                         return false;
1030                 }
1031
1032                 // In case of a forum post ensure to return the original post if author and forum are on the same machine
1033                 if (!empty($item['forum_mode'])) {
1034                         $author = Contact::getById($item['author-id'], ['nurl']);
1035                         if (!empty($author['nurl'])) {
1036                                 $self = Contact::selectFirst(['uid'], ['nurl' => $author['nurl'], 'self' => true]);
1037                                 if (!empty($self['uid'])) {
1038                                         $forum_item = Item::selectFirst([], ['uri-id' => $item['uri-id'], 'uid' => $self['uid']]);
1039                                         if (DBA::isResult($item)) {
1040                                                 $item = $forum_item; 
1041                                         }
1042                                 }
1043                         }
1044                 }
1045
1046                 if (empty($item['uri-id'])) {
1047                         Logger::warning('Item without uri-id', ['item' => $item]);
1048                         return false;
1049                 }
1050
1051                 if (empty($type)) {
1052                         $condition = ['item-uri' => $item['uri'], 'protocol' => Conversation::PARCEL_ACTIVITYPUB];
1053                         $conversation = DBA::selectFirst('conversation', ['source'], $condition);
1054                         if (DBA::isResult($conversation)) {
1055                                 $data = json_decode($conversation['source'], true);
1056                                 if (!empty($data['type'])) {
1057                                         if (in_array($data['type'], ['Create', 'Update'])) {
1058                                                 if ($object_mode) {
1059                                                         unset($data['@context']);
1060                                                         unset($data['signature']);
1061                                                 }
1062                                                 Logger::info('Return stored conversation', ['item' => $item_id]);
1063                                                 return $data;
1064                                         } elseif (in_array('as:' . $data['type'], Receiver::CONTENT_TYPES)) {
1065                                                 if (!empty($data['@context'])) {
1066                                                         $context = $data['@context'];
1067                                                         unset($data['@context']);
1068                                                 }
1069                                                 unset($data['actor']);
1070                                                 $object = $data;
1071                                         }
1072                                 }
1073                         }
1074
1075                         $type = self::getTypeOfItem($item);
1076                 }
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 }