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