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