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