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