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