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