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