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