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