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