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