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