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