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