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