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