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