]> git.mxchange.org Git - friendica.git/blob - src/Protocol/ActivityPub/Transmitter.php
daed50d0b2c47a8839bc5b925b2b332ef03faa62
[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                         Contact::update(['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                         Contact::update(['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                 if (!DBA::isResult($reply)) {
881                         $reply = $mail;
882                 }
883
884                 // Making the post more compatible for Mastodon by:
885                 // - Making it a note and not an article (no title)
886                 // - Moving the title into the "summary" field that is used as a "content warning"
887
888                 if (!$use_title) {
889                         $mail['body']         = '[abstract]' . $mail['title'] . "[/abstract]\n" . $mail['body'];
890                         $mail['title']        = '';
891                 }
892
893                 $mail['author-link']      = $mail['owner-link'] = $mail['from-url'];
894                 $mail['owner-id']         = $mail['author-id'];
895                 $mail['allow_cid']        = '<'.$mail['contact-id'].'>';
896                 $mail['allow_gid']        = '';
897                 $mail['deny_cid']         = '';
898                 $mail['deny_gid']         = '';
899                 $mail['private']          = Item::PRIVATE;
900                 $mail['deleted']          = false;
901                 $mail['edited']           = $mail['created'];
902                 $mail['plink']            = DI::baseUrl() . '/message/' . $mail['id'];
903                 $mail['parent-uri']       = $reply['uri'];
904                 $mail['parent-uri-id']    = $reply['uri-id'];
905                 $mail['parent-author-id'] = Contact::getIdForURL($reply['from-url'], 0, false);
906                 $mail['gravity']          = ($mail['reply'] ? GRAVITY_COMMENT: GRAVITY_PARENT);
907                 $mail['event-type']       = '';
908                 $mail['language']         = '';
909                 $mail['parent']           = 0;
910
911                 return $mail;
912         }
913
914         /**
915          * Creates an activity array for a given mail id
916          *
917          * @param integer $mail_id
918          * @param boolean $object_mode Is the activity item is used inside another object?
919          *
920          * @return array of activity
921          * @throws \Exception
922          */
923         public static function createActivityFromMail($mail_id, $object_mode = false)
924         {
925                 $mail = self::ItemArrayFromMail($mail_id);
926                 if (empty($mail)) {
927                         return [];
928                 }
929                 $object = self::createNote($mail);
930
931                 if (!$object_mode) {
932                         $data = ['@context' => ActivityPub::CONTEXT];
933                 } else {
934                         $data = [];
935                 }
936
937                 $data['id'] = $mail['uri'] . '/Create';
938                 $data['type'] = 'Create';
939                 $data['actor'] = $mail['author-link'];
940                 $data['published'] = DateTimeFormat::utc($mail['created'] . '+00:00', DateTimeFormat::ATOM);
941                 $data['instrument'] = self::getService();
942                 $data = array_merge($data, self::createPermissionBlockForItem($mail, true));
943
944                 if (empty($data['to']) && !empty($data['cc'])) {
945                         $data['to'] = $data['cc'];
946                 }
947
948                 if (empty($data['to']) && !empty($data['bcc'])) {
949                         $data['to'] = $data['bcc'];
950                 }
951
952                 unset($data['cc']);
953                 unset($data['bcc']);
954
955                 $object['to'] = $data['to'];
956                 $object['tag'] = [['type' => 'Mention', 'href' => $object['to'][0], 'name' => '']];
957
958                 unset($object['cc']);
959                 unset($object['bcc']);
960
961                 $data['directMessage'] = true;
962
963                 $data['object'] = $object;
964
965                 $owner = User::getOwnerDataById($mail['uid']);
966
967                 if (!$object_mode && !empty($owner)) {
968                         return LDSignature::sign($data, $owner);
969                 } else {
970                         return $data;
971                 }
972         }
973
974         /**
975          * Returns the activity type of a given item
976          *
977          * @param array $item
978          *
979          * @return string with activity type
980          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
981          * @throws \ImagickException
982          */
983         private static function getTypeOfItem($item)
984         {
985                 $reshared = false;
986
987                 // Only check for a reshare, if it is a real reshare and no quoted reshare
988                 if (strpos($item['body'], "[share") === 0) {
989                         $announce = self::getAnnounceArray($item);
990                         $reshared = !empty($announce);
991                 }
992
993                 if ($reshared) {
994                         $type = 'Announce';
995                 } elseif ($item['verb'] == Activity::POST) {
996                         if ($item['created'] == $item['edited']) {
997                                 $type = 'Create';
998                         } else {
999                                 $type = 'Update';
1000                         }
1001                 } elseif ($item['verb'] == Activity::LIKE) {
1002                         $type = 'Like';
1003                 } elseif ($item['verb'] == Activity::DISLIKE) {
1004                         $type = 'Dislike';
1005                 } elseif ($item['verb'] == Activity::ATTEND) {
1006                         $type = 'Accept';
1007                 } elseif ($item['verb'] == Activity::ATTENDNO) {
1008                         $type = 'Reject';
1009                 } elseif ($item['verb'] == Activity::ATTENDMAYBE) {
1010                         $type = 'TentativeAccept';
1011                 } elseif ($item['verb'] == Activity::FOLLOW) {
1012                         $type = 'Follow';
1013                 } elseif ($item['verb'] == Activity::TAG) {
1014                         $type = 'Add';
1015                 } elseif ($item['verb'] == Activity::ANNOUNCE) {
1016                         $type = 'Announce';
1017                 } else {
1018                         $type = '';
1019                 }
1020
1021                 return $type;
1022         }
1023
1024         /**
1025          * Creates the activity or fetches it from the cache
1026          *
1027          * @param integer $item_id
1028          * @param boolean $force Force new cache entry
1029          *
1030          * @return array with the activity
1031          * @throws \Exception
1032          */
1033         public static function createCachedActivityFromItem($item_id, $force = false)
1034         {
1035                 $cachekey = 'APDelivery:createActivity:' . $item_id;
1036
1037                 if (!$force) {
1038                         $data = DI::cache()->get($cachekey);
1039                         if (!is_null($data)) {
1040                                 return $data;
1041                         }
1042                 }
1043
1044                 $data = self::createActivityFromItem($item_id);
1045
1046                 DI::cache()->set($cachekey, $data, Duration::QUARTER_HOUR);
1047                 return $data;
1048         }
1049
1050         /**
1051          * Creates an activity array for a given item id
1052          *
1053          * @param integer $item_id
1054          * @param boolean $object_mode Is the activity item is used inside another object?
1055          *
1056          * @return false|array
1057          * @throws \Exception
1058          */
1059         public static function createActivityFromItem(int $item_id, bool $object_mode = false)
1060         {
1061                 Logger::info('Fetching activity', ['item' => $item_id]);
1062                 $item = Post::selectFirst(Item::DELIVER_FIELDLIST, ['id' => $item_id, 'parent-network' => Protocol::NATIVE_SUPPORT]);
1063                 if (!DBA::isResult($item)) {
1064                         return false;
1065                 }
1066
1067                 // In case of a forum post ensure to return the original post if author and forum are on the same machine
1068                 if (($item['gravity'] == GRAVITY_PARENT) && !empty($item['forum_mode'])) {
1069                         $author = Contact::getById($item['author-id'], ['nurl']);
1070                         if (!empty($author['nurl'])) {
1071                                 $self = Contact::selectFirst(['uid'], ['nurl' => $author['nurl'], 'self' => true]);
1072                                 if (!empty($self['uid'])) {
1073                                         $forum_item = Post::selectFirst(Item::DELIVER_FIELDLIST, ['uri-id' => $item['uri-id'], 'uid' => $self['uid']]);
1074                                         if (DBA::isResult($forum_item)) {
1075                                                 $item = $forum_item;
1076                                         }
1077                                 }
1078                         }
1079                 }
1080
1081                 if (empty($item['uri-id'])) {
1082                         Logger::warning('Item without uri-id', ['item' => $item]);
1083                         return false;
1084                 }
1085
1086                 if (!$item['deleted']) {
1087                         $condition = ['item-uri' => $item['uri'], 'protocol' => Conversation::PARCEL_ACTIVITYPUB];
1088                         $conversation = DBA::selectFirst('conversation', ['source'], $condition);
1089                         if (!$item['origin'] && DBA::isResult($conversation)) {
1090                                 $data = json_decode($conversation['source'], true);
1091                                 if (!empty($data['type'])) {
1092                                         if (in_array($data['type'], ['Create', 'Update'])) {
1093                                                 if ($object_mode) {
1094                                                         unset($data['@context']);
1095                                                         unset($data['signature']);
1096                                                 }
1097                                                 Logger::info('Return stored conversation', ['item' => $item_id]);
1098                                                 return $data;
1099                                         } elseif (in_array('as:' . $data['type'], Receiver::CONTENT_TYPES)) {
1100                                                 if (!empty($data['@context'])) {
1101                                                         $context = $data['@context'];
1102                                                         unset($data['@context']);
1103                                                 }
1104                                                 unset($data['actor']);
1105                                                 $object = $data;
1106                                         }
1107                                 }
1108                         }
1109                 }
1110
1111                 $type = self::getTypeOfItem($item);
1112
1113                 if (!$object_mode) {
1114                         $data = ['@context' => $context ?? ActivityPub::CONTEXT];
1115
1116                         if ($item['deleted'] && ($item['gravity'] == GRAVITY_ACTIVITY)) {
1117                                 $type = 'Undo';
1118                         } elseif ($item['deleted']) {
1119                                 $type = 'Delete';
1120                         }
1121                 } else {
1122                         $data = [];
1123                 }
1124
1125                 if ($type == 'Delete') {
1126                         $data['id'] = Item::newURI($item['uid'], $item['guid']) . '/' . $type;;
1127                 } elseif (($item['gravity'] == GRAVITY_ACTIVITY) && ($type != 'Undo')) {
1128                         $data['id'] = $item['uri'];
1129                 } else {
1130                         $data['id'] = $item['uri'] . '/' . $type;
1131                 }
1132
1133                 $data['type'] = $type;
1134
1135                 if (($type != 'Announce') || ($item['gravity'] != GRAVITY_PARENT)) {
1136                         $data['actor'] = $item['author-link'];
1137                 } else {
1138                         $data['actor'] = $item['owner-link'];
1139                 }
1140
1141                 $data['published'] = DateTimeFormat::utc($item['created'] . '+00:00', DateTimeFormat::ATOM);
1142
1143                 $data['instrument'] = self::getService();
1144
1145                 $data = array_merge($data, self::createPermissionBlockForItem($item, false));
1146
1147                 if (in_array($data['type'], ['Create', 'Update', 'Delete'])) {
1148                         $data['object'] = $object ?? self::createNote($item);
1149                 } elseif ($data['type'] == 'Add') {
1150                         $data = self::createAddTag($item, $data);
1151                 } elseif ($data['type'] == 'Announce') {
1152                         if ($item['verb'] == ACTIVITY::ANNOUNCE) {
1153                                 $data['object'] = $item['thr-parent'];
1154                         } else {
1155                                 $data = self::createAnnounce($item, $data);
1156                         }
1157                 } elseif ($data['type'] == 'Follow') {
1158                         $data['object'] = $item['parent-uri'];
1159                 } elseif ($data['type'] == 'Undo') {
1160                         $data['object'] = self::createActivityFromItem($item_id, true);
1161                 } else {
1162                         $data['diaspora:guid'] = $item['guid'];
1163                         if (!empty($item['signed_text'])) {
1164                                 $data['diaspora:like'] = $item['signed_text'];
1165                         }
1166                         $data['object'] = $item['thr-parent'];
1167                 }
1168
1169                 if (!empty($item['contact-uid'])) {
1170                         $uid = $item['contact-uid'];
1171                 } else {
1172                         $uid = $item['uid'];
1173                 }
1174
1175                 $owner = User::getOwnerDataById($uid);
1176
1177                 Logger::info('Fetched activity', ['item' => $item_id, 'uid' => $uid]);
1178
1179                 // We don't sign if we aren't the actor. This is important for relaying content especially for forums
1180                 if (!$object_mode && !empty($owner) && ($data['actor'] == $owner['url'])) {
1181                         return LDSignature::sign($data, $owner);
1182                 } else {
1183                         return $data;
1184                 }
1185
1186                 /// @todo Create "conversation" entry
1187         }
1188
1189         /**
1190          * Creates a location entry for a given item array
1191          *
1192          * @param array $item
1193          *
1194          * @return array with location array
1195          */
1196         private static function createLocation($item)
1197         {
1198                 $location = ['type' => 'Place'];
1199
1200                 if (!empty($item['location'])) {
1201                         $location['name'] = $item['location'];
1202                 }
1203
1204                 $coord = [];
1205
1206                 if (empty($item['coord'])) {
1207                         $coord = Map::getCoordinates($item['location']);
1208                 } else {
1209                         $coords = explode(' ', $item['coord']);
1210                         if (count($coords) == 2) {
1211                                 $coord = ['lat' => $coords[0], 'lon' => $coords[1]];
1212                         }
1213                 }
1214
1215                 if (!empty($coord['lat']) && !empty($coord['lon'])) {
1216                         $location['latitude'] = $coord['lat'];
1217                         $location['longitude'] = $coord['lon'];
1218                 }
1219
1220                 return $location;
1221         }
1222
1223         /**
1224          * Returns a tag array for a given item array
1225          *
1226          * @param array $item
1227          *
1228          * @return array of tags
1229          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1230          */
1231         private static function createTagList($item)
1232         {
1233                 $tags = [];
1234
1235                 $terms = Tag::getByURIId($item['uri-id'], [Tag::HASHTAG, Tag::MENTION, Tag::IMPLICIT_MENTION, Tag::EXCLUSIVE_MENTION]);
1236                 foreach ($terms as $term) {
1237                         if ($term['type'] == Tag::HASHTAG) {
1238                                 $url = DI::baseUrl() . '/search?tag=' . urlencode($term['name']);
1239                                 $tags[] = ['type' => 'Hashtag', 'href' => $url, 'name' => '#' . $term['name']];
1240                         } else {
1241                                 $contact = Contact::getByURL($term['url'], false, ['addr']);
1242                                 if (empty($contact)) {
1243                                         continue;
1244                                 }
1245                                 if (!empty($contact['addr'])) {
1246                                         $mention = '@' . $contact['addr'];
1247                                 } else {
1248                                         $mention = '@' . $term['url'];
1249                                 }
1250
1251                                 $tags[] = ['type' => 'Mention', 'href' => $term['url'], 'name' => $mention];
1252                         }
1253                 }
1254
1255                 $announce = self::getAnnounceArray($item);
1256                 // Mention the original author upon commented reshares
1257                 if (!empty($announce['comment'])) {
1258                         $tags[] = ['type' => 'Mention', 'href' => $announce['actor']['url'], 'name' => '@' . $announce['actor']['addr']];
1259                 }
1260
1261                 return $tags;
1262         }
1263
1264         /**
1265          * Adds attachment data to the JSON document
1266          *
1267          * @param array  $item Data of the item that is to be posted
1268          * @param string $type Object type
1269          *
1270          * @return array with attachment data
1271          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1272          */
1273         private static function createAttachmentList($item, $type)
1274         {
1275                 $attachments = [];
1276
1277                 $uriids = [$item['uri-id']];
1278                 $shared = BBCode::fetchShareAttributes($item['body']);
1279                 if (!empty($shared['guid'])) {
1280                         $shared_item = Post::selectFirst(['uri-id'], ['guid' => $shared['guid']]);
1281                         if (!empty($shared_item['uri-id'])) {
1282                                 $uriids[] = $shared_item['uri-id'];
1283                         }
1284                 }
1285
1286                 $urls = [];
1287                 foreach ($uriids as $uriid) {
1288                         foreach (Post\Media::getByURIId($uriid, [Post\Media::DOCUMENT, Post\Media::TORRENT]) as $attachment) {
1289                                 if (in_array($attachment['url'], $urls)) {
1290                                         continue;
1291                                 }
1292                                 $urls[] = $attachment['url'];
1293
1294                                 $attach = ['type' => 'Document',
1295                                         'mediaType' => $attachment['mimetype'],
1296                                         'url' => $attachment['url'],
1297                                         'name' => $attachment['description']];
1298
1299                                 if (!empty($attachment['height'])) {
1300                                         $attach['height'] = $attachment['height'];
1301                                 }
1302
1303                                 if (!empty($attachment['width'])) {
1304                                         $attach['width'] = $attachment['width'];
1305                                 }
1306
1307                                 if (!empty($attachment['preview'])) {
1308                                         $attach['image'] = $attachment['preview'];
1309                                 }
1310
1311                                 $attachments[] = $attach;
1312                         }
1313                 }
1314
1315                 if ($type != 'Note') {
1316                         return $attachments;
1317                 }
1318
1319                 foreach ($uriids as $uriid) {
1320                         foreach (Post\Media::getByURIId($uriid, [Post\Media::AUDIO, Post\Media::IMAGE, Post\Media::VIDEO]) as $attachment) {
1321                                 if (in_array($attachment['url'], $urls)) {
1322                                         continue;
1323                                 }
1324                                 $urls[] = $attachment['url'];
1325
1326                                 $attach = ['type' => 'Document',
1327                                         'mediaType' => $attachment['mimetype'],
1328                                         'url' => $attachment['url'],
1329                                         'name' => $attachment['description']];
1330
1331                                 if (!empty($attachment['height'])) {
1332                                         $attach['height'] = $attachment['height'];
1333                                 }
1334
1335                                 if (!empty($attachment['width'])) {
1336                                         $attach['width'] = $attachment['width'];
1337                                 }
1338
1339                                 if (!empty($attachment['preview'])) {
1340                                         $attach['image'] = $attachment['preview'];
1341                                 }
1342
1343                                 $attachments[] = $attach;
1344                         }
1345                         // Currently deactivated, since it creates side effects on Mastodon and Pleroma.
1346                         // It will be activated, once this cleared.
1347                         /*
1348                         foreach (Post\Media::getByURIId($uriid, [Post\Media::HTML]) as $attachment) {
1349                                 if (in_array($attachment['url'], $urls)) {
1350                                         continue;
1351                                 }
1352                                 $urls[] = $attachment['url'];
1353
1354                                 $attachments[] = ['type' => 'Page',
1355                                         'mediaType' => $attachment['mimetype'],
1356                                         'url' => $attachment['url'],
1357                                         'name' => $attachment['description']];
1358                         }*/
1359                 }
1360
1361                 return $attachments;
1362         }
1363
1364         /**
1365          * Callback function to replace a Friendica style mention in a mention for a summary
1366          *
1367          * @param array $match Matching values for the callback
1368          * @return string Replaced mention
1369          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1370          */
1371         private static function mentionAddrCallback($match)
1372         {
1373                 if (empty($match[1])) {
1374                         return '';
1375                 }
1376
1377                 $data = Contact::getByURL($match[1], false, ['addr']);
1378                 if (empty($data['addr'])) {
1379                         return $match[0];
1380                 }
1381
1382                 return '@' . $data['addr'];
1383         }
1384
1385         /**
1386          * Remove image elements since they are added as attachment
1387          *
1388          * @param string $body
1389          *
1390          * @return string with removed images
1391          */
1392         private static function removePictures($body)
1393         {
1394                 // Simplify image codes
1395                 $body = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '[img]$3[/img]', $body);
1396                 $body = preg_replace("/\[img\=(.*?)\](.*?)\[\/img\]/ism", '[img]$1[/img]', $body);
1397
1398                 // Now remove local links
1399                 $body = preg_replace_callback(
1400                         '/\[url=([^\[\]]*)\]\[img\](.*)\[\/img\]\[\/url\]/Usi',
1401                         function ($match) {
1402                                 // We remove the link when it is a link to a local photo page
1403                                 if (Photo::isLocalPage($match[1])) {
1404                                         return '';
1405                                 }
1406                                 // otherwise we just return the link
1407                                 return '[url]' . $match[1] . '[/url]';
1408                         },
1409                         $body
1410                 );
1411
1412                 // Remove all pictures
1413                 $body = preg_replace("/\[img\]([^\[\]]*)\[\/img\]/Usi", '', $body);
1414
1415                 return $body;
1416         }
1417
1418         /**
1419          * Fetches the "context" value for a givem item array from the "conversation" table
1420          *
1421          * @param array $item
1422          *
1423          * @return string with context url
1424          * @throws \Exception
1425          */
1426         private static function fetchContextURLForItem($item)
1427         {
1428                 $conversation = DBA::selectFirst('conversation', ['conversation-href', 'conversation-uri'], ['item-uri' => $item['parent-uri']]);
1429                 if (DBA::isResult($conversation) && !empty($conversation['conversation-href'])) {
1430                         $context_uri = $conversation['conversation-href'];
1431                 } elseif (DBA::isResult($conversation) && !empty($conversation['conversation-uri'])) {
1432                         $context_uri = $conversation['conversation-uri'];
1433                 } else {
1434                         $context_uri = $item['parent-uri'] . '#context';
1435                 }
1436                 return $context_uri;
1437         }
1438
1439         /**
1440          * Returns if the post contains sensitive content ("nsfw")
1441          *
1442          * @param integer $uri_id
1443          *
1444          * @return boolean
1445          * @throws \Exception
1446          */
1447         private static function isSensitive($uri_id)
1448         {
1449                 return DBA::exists('tag-view', ['uri-id' => $uri_id, 'name' => 'nsfw']);
1450         }
1451
1452         /**
1453          * Creates event data
1454          *
1455          * @param array $item
1456          *
1457          * @return array with the event data
1458          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1459          */
1460         private static function createEvent($item)
1461         {
1462                 $event = [];
1463                 $event['name'] = $item['event-summary'];
1464                 $event['content'] = BBCode::convertForUriId($item['uri-id'], $item['event-desc'], BBCode::ACTIVITYPUB);
1465                 $event['startTime'] = DateTimeFormat::utc($item['event-start'] . '+00:00', DateTimeFormat::ATOM);
1466
1467                 if (!$item['event-nofinish']) {
1468                         $event['endTime'] = DateTimeFormat::utc($item['event-finish'] . '+00:00', DateTimeFormat::ATOM);
1469                 }
1470
1471                 if (!empty($item['event-location'])) {
1472                         $item['location'] = $item['event-location'];
1473                         $event['location'] = self::createLocation($item);
1474                 }
1475
1476                 $event['dfrn:adjust'] = (bool)$item['event-adjust'];
1477
1478                 return $event;
1479         }
1480
1481         /**
1482          * Creates a note/article object array
1483          *
1484          * @param array $item
1485          *
1486          * @return array with the object data
1487          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1488          * @throws \ImagickException
1489          */
1490         public static function createNote($item)
1491         {
1492                 if (empty($item)) {
1493                         return [];
1494                 }
1495
1496                 if ($item['event-type'] == 'event') {
1497                         $type = 'Event';
1498                 } elseif (!empty($item['title'])) {
1499                         $type = 'Article';
1500                 } else {
1501                         $type = 'Note';
1502                 }
1503
1504                 if ($item['deleted']) {
1505                         $type = 'Tombstone';
1506                 }
1507
1508                 $data = [];
1509                 $data['id'] = $item['uri'];
1510                 $data['type'] = $type;
1511
1512                 if ($item['deleted']) {
1513                         return $data;
1514                 }
1515
1516                 $data['summary'] = BBCode::toPlaintext(BBCode::getAbstract($item['body'], Protocol::ACTIVITYPUB));
1517
1518                 if ($item['uri'] != $item['thr-parent']) {
1519                         $data['inReplyTo'] = $item['thr-parent'];
1520                 } else {
1521                         $data['inReplyTo'] = null;
1522                 }
1523
1524                 $data['diaspora:guid'] = $item['guid'];
1525                 $data['published'] = DateTimeFormat::utc($item['created'] . '+00:00', DateTimeFormat::ATOM);
1526
1527                 if ($item['created'] != $item['edited']) {
1528                         $data['updated'] = DateTimeFormat::utc($item['edited'] . '+00:00', DateTimeFormat::ATOM);
1529                 }
1530
1531                 $data['url'] = $item['plink'];
1532                 $data['attributedTo'] = $item['author-link'];
1533                 $data['sensitive'] = self::isSensitive($item['uri-id']);
1534                 $data['context'] = self::fetchContextURLForItem($item);
1535
1536                 if (!empty($item['title'])) {
1537                         $data['name'] = BBCode::toPlaintext($item['title'], false);
1538                 }
1539
1540                 $permission_block = self::createPermissionBlockForItem($item, false);
1541
1542                 $body = $item['body'];
1543
1544                 if ($type == 'Note') {
1545                         $body = $item['raw-body'] ?? self::removePictures($body);
1546                 }
1547
1548                 /**
1549                  * @todo Improve the automated summary
1550                  * This part is currently deactivated. The automated summary seems to be more
1551                  * confusing than helping. But possibly we will find a better way.
1552                  * So the code is left here for now as a reminder
1553                  *
1554                  * } elseif (($type == 'Article') && empty($data['summary'])) {
1555                  *              $regexp = "/[@!]\[url\=([^\[\]]*)\].*?\[\/url\]/ism";
1556                  *              $summary = preg_replace_callback($regexp, ['self', 'mentionAddrCallback'], $body);
1557                  *              $data['summary'] = BBCode::toPlaintext(Plaintext::shorten(self::removePictures($summary), 1000));
1558                  * }
1559                  */
1560
1561                 if (empty($item['uid']) || !Feature::isEnabled($item['uid'], 'explicit_mentions')) {
1562                         $body = self::prependMentions($body, $item['uri-id'], $item['author-link']);
1563                 }
1564
1565                 if ($type == 'Event') {
1566                         $data = array_merge($data, self::createEvent($item));
1567                 } else {
1568                         $body = BBCode::setMentionsToNicknames($body);
1569
1570                         $data['content'] = BBCode::convertForUriId($item['uri-id'], $body, BBCode::ACTIVITYPUB);
1571                 }
1572
1573                 // The regular "content" field does contain a minimized HTML. This is done since systems like
1574                 // Mastodon has got problems with - for example - embedded pictures.
1575                 // The contentMap does contain the unmodified HTML.
1576                 $language = self::getLanguage($item);
1577                 if (!empty($language)) {
1578                         $richbody = BBCode::setMentionsToNicknames($item['body'] ?? '');
1579                         $richbody = BBCode::removeAttachment($richbody);
1580
1581                         $data['contentMap'][$language] = BBCode::convertForUriId($item['uri-id'], $richbody, BBCode::EXTERNAL);
1582                 }
1583
1584                 $data['source'] = ['content' => $item['body'], 'mediaType' => "text/bbcode"];
1585
1586                 if (!empty($item['signed_text']) && ($item['uri'] != $item['thr-parent'])) {
1587                         $data['diaspora:comment'] = $item['signed_text'];
1588                 }
1589
1590                 $data['attachment'] = self::createAttachmentList($item, $type);
1591                 $data['tag'] = self::createTagList($item);
1592
1593                 if (empty($data['location']) && (!empty($item['coord']) || !empty($item['location']))) {
1594                         $data['location'] = self::createLocation($item);
1595                 }
1596
1597                 if (!empty($item['app'])) {
1598                         $data['generator'] = ['type' => 'Application', 'name' => $item['app']];
1599                 }
1600
1601                 $data = array_merge($data, $permission_block);
1602
1603                 return $data;
1604         }
1605
1606         /**
1607          * Fetches the language from the post, the user or the system.
1608          *
1609          * @param array $item
1610          *
1611          * @return string language string
1612          */
1613         private static function getLanguage(array $item)
1614         {
1615                 // Try to fetch the language from the post itself
1616                 if (!empty($item['language'])) {
1617                         $languages = array_keys(json_decode($item['language'], true));
1618                         if (!empty($languages[0])) {
1619                                 return $languages[0];
1620                         }
1621                 }
1622
1623                 // Otherwise use the user's language
1624                 if (!empty($item['uid'])) {
1625                         $user = DBA::selectFirst('user', ['language'], ['uid' => $item['uid']]);
1626                         if (!empty($user['language'])) {
1627                                 return $user['language'];
1628                         }
1629                 }
1630
1631                 // And finally just use the system language
1632                 return DI::config()->get('system', 'language');
1633         }
1634
1635         /**
1636          * Creates an an "add tag" entry
1637          *
1638          * @param array $item
1639          * @param array $data activity data
1640          *
1641          * @return array with activity data for adding tags
1642          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1643          * @throws \ImagickException
1644          */
1645         private static function createAddTag($item, $data)
1646         {
1647                 $object = XML::parseString($item['object']);
1648                 $target = XML::parseString($item["target"]);
1649
1650                 $data['diaspora:guid'] = $item['guid'];
1651                 $data['actor'] = $item['author-link'];
1652                 $data['target'] = (string)$target->id;
1653                 $data['summary'] = BBCode::toPlaintext($item['body']);
1654                 $data['object'] = ['id' => (string)$object->id, 'type' => 'tag', 'name' => (string)$object->title, 'content' => (string)$object->content];
1655
1656                 return $data;
1657         }
1658
1659         /**
1660          * Creates an announce object entry
1661          *
1662          * @param array $item
1663          * @param array $data activity data
1664          *
1665          * @return array with activity data
1666          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1667          * @throws \ImagickException
1668          */
1669         private static function createAnnounce($item, $data)
1670         {
1671                 $orig_body = $item['body'];
1672                 $announce = self::getAnnounceArray($item);
1673                 if (empty($announce)) {
1674                         $data['type'] = 'Create';
1675                         $data['object'] = self::createNote($item);
1676                         return $data;
1677                 }
1678
1679                 if (empty($announce['comment'])) {
1680                         // Pure announce, without a quote
1681                         $data['type'] = 'Announce';
1682                         $data['object'] = $announce['object']['uri'];
1683                         return $data;
1684                 }
1685
1686                 // Quote
1687                 $data['type'] = 'Create';
1688                 $item['body'] = $announce['comment'] . "\n" . $announce['object']['plink'];
1689                 $data['object'] = self::createNote($item);
1690
1691                 /// @todo Finally descide how to implement this in AP. This is a possible way:
1692                 $data['object']['attachment'][] = self::createNote($announce['object']);
1693
1694                 $data['object']['source']['content'] = $orig_body;
1695                 return $data;
1696         }
1697
1698         /**
1699          * Return announce related data if the item is an annunce
1700          *
1701          * @param array $item
1702          *
1703          * @return array
1704          */
1705         public static function getAnnounceArray($item)
1706         {
1707                 $reshared = Item::getShareArray($item);
1708                 if (empty($reshared['guid'])) {
1709                         return [];
1710                 }
1711
1712                 $reshared_item = Post::selectFirst(Item::DELIVER_FIELDLIST, ['guid' => $reshared['guid']]);
1713                 if (!DBA::isResult($reshared_item)) {
1714                         return [];
1715                 }
1716
1717                 if (!in_array($reshared_item['network'], [Protocol::ACTIVITYPUB, Protocol::DFRN])) {
1718                         return [];
1719                 }
1720
1721                 $profile = APContact::getByURL($reshared_item['author-link'], false);
1722                 if (empty($profile)) {
1723                         return [];
1724                 }
1725
1726                 return ['object' => $reshared_item, 'actor' => $profile, 'comment' => $reshared['comment']];
1727         }
1728
1729         /**
1730          * Checks if the provided item array is an announce
1731          *
1732          * @param array $item
1733          *
1734          * @return boolean
1735          */
1736         public static function isAnnounce($item)
1737         {
1738                 if (!empty($item['verb']) && ($item['verb'] == Activity::ANNOUNCE)) {
1739                         return true;
1740                 }
1741
1742                 $announce = self::getAnnounceArray($item);
1743                 if (empty($announce)) {
1744                         return false;
1745                 }
1746
1747                 return empty($announce['comment']);
1748         }
1749
1750         /**
1751          * Creates an activity id for a given contact id
1752          *
1753          * @param integer $cid Contact ID of target
1754          *
1755          * @return bool|string activity id
1756          */
1757         public static function activityIDFromContact($cid)
1758         {
1759                 $contact = DBA::selectFirst('contact', ['uid', 'id', 'created'], ['id' => $cid]);
1760                 if (!DBA::isResult($contact)) {
1761                         return false;
1762                 }
1763
1764                 $hash = hash('ripemd128', $contact['uid'].'-'.$contact['id'].'-'.$contact['created']);
1765                 $uuid = substr($hash, 0, 8). '-' . substr($hash, 8, 4) . '-' . substr($hash, 12, 4) . '-' . substr($hash, 16, 4) . '-' . substr($hash, 20, 12);
1766                 return DI::baseUrl() . '/activity/' . $uuid;
1767         }
1768
1769         /**
1770          * Transmits a contact suggestion to a given inbox
1771          *
1772          * @param integer $uid           User ID
1773          * @param string  $inbox         Target inbox
1774          * @param integer $suggestion_id Suggestion ID
1775          *
1776          * @return boolean was the transmission successful?
1777          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1778          */
1779         public static function sendContactSuggestion($uid, $inbox, $suggestion_id)
1780         {
1781                 $owner = User::getOwnerDataById($uid);
1782
1783                 $suggestion = DI::fsuggest()->getById($suggestion_id);
1784
1785                 $data = ['@context' => ActivityPub::CONTEXT,
1786                         'id' => DI::baseUrl() . '/activity/' . System::createGUID(),
1787                         'type' => 'Announce',
1788                         'actor' => $owner['url'],
1789                         'object' => $suggestion->url,
1790                         'content' => $suggestion->note,
1791                         'instrument' => self::getService(),
1792                         'to' => [ActivityPub::PUBLIC_COLLECTION],
1793                         'cc' => []];
1794
1795                 $signed = LDSignature::sign($data, $owner);
1796
1797                 Logger::log('Deliver profile deletion for user ' . $uid . ' to ' . $inbox . ' via ActivityPub', Logger::DEBUG);
1798                 return HTTPSignature::transmit($signed, $inbox, $uid);
1799         }
1800
1801         /**
1802          * Transmits a profile relocation to a given inbox
1803          *
1804          * @param integer $uid   User ID
1805          * @param string  $inbox Target inbox
1806          *
1807          * @return boolean was the transmission successful?
1808          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1809          */
1810         public static function sendProfileRelocation($uid, $inbox)
1811         {
1812                 $owner = User::getOwnerDataById($uid);
1813
1814                 $data = ['@context' => ActivityPub::CONTEXT,
1815                         'id' => DI::baseUrl() . '/activity/' . System::createGUID(),
1816                         'type' => 'dfrn:relocate',
1817                         'actor' => $owner['url'],
1818                         'object' => $owner['url'],
1819                         'published' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
1820                         'instrument' => self::getService(),
1821                         'to' => [ActivityPub::PUBLIC_COLLECTION],
1822                         'cc' => []];
1823
1824                 $signed = LDSignature::sign($data, $owner);
1825
1826                 Logger::log('Deliver profile relocation for user ' . $uid . ' to ' . $inbox . ' via ActivityPub', Logger::DEBUG);
1827                 return HTTPSignature::transmit($signed, $inbox, $uid);
1828         }
1829
1830         /**
1831          * Transmits a profile deletion to a given inbox
1832          *
1833          * @param integer $uid   User ID
1834          * @param string  $inbox Target inbox
1835          *
1836          * @return boolean was the transmission successful?
1837          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1838          */
1839         public static function sendProfileDeletion($uid, $inbox)
1840         {
1841                 $owner = User::getOwnerDataById($uid);
1842
1843                 if (empty($owner)) {
1844                         Logger::error('No owner data found, the deletion message cannot be processed.', ['user' => $uid]);
1845                         return false;
1846                 }
1847
1848                 if (empty($owner['uprvkey'])) {
1849                         Logger::error('No private key for owner found, the deletion message cannot be processed.', ['user' => $uid]);
1850                         return false;
1851                 }
1852
1853                 $data = ['@context' => ActivityPub::CONTEXT,
1854                         'id' => DI::baseUrl() . '/activity/' . System::createGUID(),
1855                         'type' => 'Delete',
1856                         'actor' => $owner['url'],
1857                         'object' => $owner['url'],
1858                         'published' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
1859                         'instrument' => self::getService(),
1860                         'to' => [ActivityPub::PUBLIC_COLLECTION],
1861                         'cc' => []];
1862
1863                 $signed = LDSignature::sign($data, $owner);
1864
1865                 Logger::log('Deliver profile deletion for user ' . $uid . ' to ' . $inbox . ' via ActivityPub', Logger::DEBUG);
1866                 return HTTPSignature::transmit($signed, $inbox, $uid);
1867         }
1868
1869         /**
1870          * Transmits a profile change to a given inbox
1871          *
1872          * @param integer $uid   User ID
1873          * @param string  $inbox Target inbox
1874          *
1875          * @return boolean was the transmission successful?
1876          * @throws HTTPException\InternalServerErrorException
1877          * @throws HTTPException\NotFoundException
1878          * @throws \ImagickException
1879          */
1880         public static function sendProfileUpdate(int $uid, string $inbox): bool
1881         {
1882                 $owner = User::getOwnerDataById($uid);
1883                 $profile = APContact::getByURL($owner['url']);
1884
1885                 $data = ['@context' => ActivityPub::CONTEXT,
1886                         'id' => DI::baseUrl() . '/activity/' . System::createGUID(),
1887                         'type' => 'Update',
1888                         'actor' => $owner['url'],
1889                         'object' => self::getProfile($uid),
1890                         'published' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
1891                         'instrument' => self::getService(),
1892                         'to' => [$profile['followers']],
1893                         'cc' => []];
1894
1895                 $signed = LDSignature::sign($data, $owner);
1896
1897                 Logger::log('Deliver profile update for user ' . $uid . ' to ' . $inbox . ' via ActivityPub', Logger::DEBUG);
1898                 return HTTPSignature::transmit($signed, $inbox, $uid);
1899         }
1900
1901         /**
1902          * Transmits a given activity to a target
1903          *
1904          * @param string  $activity Type name
1905          * @param string  $target   Target profile
1906          * @param integer $uid      User ID
1907          * @return bool
1908          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1909          * @throws \ImagickException
1910          * @throws \Exception
1911          */
1912         public static function sendActivity($activity, $target, $uid, $id = '')
1913         {
1914                 $profile = APContact::getByURL($target);
1915                 if (empty($profile['inbox'])) {
1916                         Logger::warning('No inbox found for target', ['target' => $target, 'profile' => $profile]);
1917                         return;
1918                 }
1919
1920                 $owner = User::getOwnerDataById($uid);
1921
1922                 if (empty($id)) {
1923                         $id = DI::baseUrl() . '/activity/' . System::createGUID();
1924                 }
1925
1926                 $data = ['@context' => ActivityPub::CONTEXT,
1927                         'id' => $id,
1928                         'type' => $activity,
1929                         'actor' => $owner['url'],
1930                         'object' => $profile['url'],
1931                         'instrument' => self::getService(),
1932                         'to' => [$profile['url']]];
1933
1934                 Logger::log('Sending activity ' . $activity . ' to ' . $target . ' for user ' . $uid, Logger::DEBUG);
1935
1936                 $signed = LDSignature::sign($data, $owner);
1937                 return HTTPSignature::transmit($signed, $profile['inbox'], $uid);
1938         }
1939
1940         /**
1941          * Transmits a "follow object" activity to a target
1942          * This is a preparation for sending automated "follow" requests when receiving "Announce" messages
1943          *
1944          * @param string  $object Object URL
1945          * @param string  $target Target profile
1946          * @param integer $uid    User ID
1947          * @return bool
1948          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1949          * @throws \ImagickException
1950          * @throws \Exception
1951          */
1952         public static function sendFollowObject($object, $target, $uid = 0)
1953         {
1954                 $profile = APContact::getByURL($target);
1955                 if (empty($profile['inbox'])) {
1956                         Logger::warning('No inbox found for target', ['target' => $target, 'profile' => $profile]);
1957                         return;
1958                 }
1959
1960                 if (empty($uid)) {
1961                         // Fetch the list of administrators
1962                         $admin_mail = explode(',', str_replace(' ', '', DI::config()->get('config', 'admin_email')));
1963
1964                         // We need to use some user as a sender. It doesn't care who it will send. We will use an administrator account.
1965                         $condition = ['verified' => true, 'blocked' => false, 'account_removed' => false, 'account_expired' => false, 'email' => $admin_mail];
1966                         $first_user = DBA::selectFirst('user', ['uid'], $condition);
1967                         $uid = $first_user['uid'];
1968                 }
1969
1970                 $condition = ['verb' => Activity::FOLLOW, 'uid' => 0, 'parent-uri' => $object,
1971                         'author-id' => Contact::getPublicIdByUserId($uid)];
1972                 if (Post::exists($condition)) {
1973                         Logger::log('Follow for ' . $object . ' for user ' . $uid . ' does already exist.', Logger::DEBUG);
1974                         return false;
1975                 }
1976
1977                 $owner = User::getOwnerDataById($uid);
1978
1979                 $data = ['@context' => ActivityPub::CONTEXT,
1980                         'id' => DI::baseUrl() . '/activity/' . System::createGUID(),
1981                         'type' => 'Follow',
1982                         'actor' => $owner['url'],
1983                         'object' => $object,
1984                         'instrument' => self::getService(),
1985                         'to' => [$profile['url']]];
1986
1987                 Logger::log('Sending follow ' . $object . ' to ' . $target . ' for user ' . $uid, Logger::DEBUG);
1988
1989                 $signed = LDSignature::sign($data, $owner);
1990                 return HTTPSignature::transmit($signed, $profile['inbox'], $uid);
1991         }
1992
1993         /**
1994          * Transmit a message that the contact request had been accepted
1995          *
1996          * @param string  $target Target profile
1997          * @param         $id
1998          * @param integer $uid    User ID
1999          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2000          * @throws \ImagickException
2001          */
2002         public static function sendContactAccept($target, $id, $uid)
2003         {
2004                 $profile = APContact::getByURL($target);
2005                 if (empty($profile['inbox'])) {
2006                         Logger::warning('No inbox found for target', ['target' => $target, 'profile' => $profile]);
2007                         return;
2008                 }
2009
2010                 $owner = User::getOwnerDataById($uid);
2011                 $data = ['@context' => ActivityPub::CONTEXT,
2012                         'id' => DI::baseUrl() . '/activity/' . System::createGUID(),
2013                         'type' => 'Accept',
2014                         'actor' => $owner['url'],
2015                         'object' => [
2016                                 'id' => (string)$id,
2017                                 'type' => 'Follow',
2018                                 'actor' => $profile['url'],
2019                                 'object' => $owner['url']
2020                         ],
2021                         'instrument' => self::getService(),
2022                         'to' => [$profile['url']]];
2023
2024                 Logger::debug('Sending accept to ' . $target . ' for user ' . $uid . ' with id ' . $id);
2025
2026                 $signed = LDSignature::sign($data, $owner);
2027                 HTTPSignature::transmit($signed, $profile['inbox'], $uid);
2028         }
2029
2030         /**
2031          * Reject a contact request or terminates the contact relation
2032          *
2033          * @param string  $target Target profile
2034          * @param         $id
2035          * @param integer $uid    User ID
2036          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2037          * @throws \ImagickException
2038          */
2039         public static function sendContactReject($target, $id, $uid)
2040         {
2041                 $profile = APContact::getByURL($target);
2042                 if (empty($profile['inbox'])) {
2043                         Logger::warning('No inbox found for target', ['target' => $target, 'profile' => $profile]);
2044                         return;
2045                 }
2046
2047                 $owner = User::getOwnerDataById($uid);
2048                 $data = ['@context' => ActivityPub::CONTEXT,
2049                         'id' => DI::baseUrl() . '/activity/' . System::createGUID(),
2050                         'type' => 'Reject',
2051                         'actor' => $owner['url'],
2052                         'object' => [
2053                                 'id' => (string)$id,
2054                                 'type' => 'Follow',
2055                                 'actor' => $profile['url'],
2056                                 'object' => $owner['url']
2057                         ],
2058                         'instrument' => self::getService(),
2059                         'to' => [$profile['url']]];
2060
2061                 Logger::debug('Sending reject to ' . $target . ' for user ' . $uid . ' with id ' . $id);
2062
2063                 $signed = LDSignature::sign($data, $owner);
2064                 HTTPSignature::transmit($signed, $profile['inbox'], $uid);
2065         }
2066
2067         /**
2068          * Transmits a message that we don't want to follow this contact anymore
2069          *
2070          * @param string  $target Target profile
2071          * @param integer $uid    User ID
2072          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
2073          * @throws \ImagickException
2074          * @throws \Exception
2075          * @return bool success
2076          */
2077         public static function sendContactUndo($target, $cid, $uid)
2078         {
2079                 $profile = APContact::getByURL($target);
2080                 if (empty($profile['inbox'])) {
2081                         Logger::warning('No inbox found for target', ['target' => $target, 'profile' => $profile]);
2082                         return false;
2083                 }
2084
2085                 $object_id = self::activityIDFromContact($cid);
2086                 if (empty($object_id)) {
2087                         return false;
2088                 }
2089
2090                 $id = DI::baseUrl() . '/activity/' . System::createGUID();
2091
2092                 $owner = User::getOwnerDataById($uid);
2093                 $data = ['@context' => ActivityPub::CONTEXT,
2094                         'id' => $id,
2095                         'type' => 'Undo',
2096                         'actor' => $owner['url'],
2097                         'object' => ['id' => $object_id, 'type' => 'Follow',
2098                                 'actor' => $owner['url'],
2099                                 'object' => $profile['url']],
2100                         'instrument' => self::getService(),
2101                         'to' => [$profile['url']]];
2102
2103                 Logger::log('Sending undo to ' . $target . ' for user ' . $uid . ' with id ' . $id, Logger::DEBUG);
2104
2105                 $signed = LDSignature::sign($data, $owner);
2106                 return HTTPSignature::transmit($signed, $profile['inbox'], $uid);
2107         }
2108
2109         private static function prependMentions($body, int $uriid, string $authorLink)
2110         {
2111                 $mentions = [];
2112
2113                 foreach (Tag::getByURIId($uriid, [Tag::IMPLICIT_MENTION]) as $tag) {
2114                         $profile = Contact::getByURL($tag['url'], false, ['addr', 'contact-type', 'nick']);
2115                         if (!empty($profile['addr'])
2116                                 && $profile['contact-type'] != Contact::TYPE_COMMUNITY
2117                                 && !strstr($body, $profile['addr'])
2118                                 && !strstr($body, $tag['url'])
2119                                 && $tag['url'] !== $authorLink
2120                         ) {
2121                                 $mentions[] = '@[url=' . $tag['url'] . ']' . $profile['nick'] . '[/url]';
2122                         }
2123                 }
2124
2125                 $mentions[] = $body;
2126
2127                 return implode(' ', $mentions);
2128         }
2129 }