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