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