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