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