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