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