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