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