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