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