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