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