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