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