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