]> git.mxchange.org Git - friendica.git/blob - src/Protocol/ActivityPub/Transmitter.php
Merge pull request #9526 from MrPetovan/bug/9525-mastodon-emojis-tag
[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                                         $item = Item::selectFirst([], ['uri-id' => $item['uri-id'], 'uid' => $self['uid']]);
999                                 }
1000                         }
1001                 }
1002
1003                 if (empty($type)) {
1004                         $condition = ['item-uri' => $item['uri'], 'protocol' => Conversation::PARCEL_ACTIVITYPUB];
1005                         $conversation = DBA::selectFirst('conversation', ['source'], $condition);
1006                         if (DBA::isResult($conversation)) {
1007                                 $data = json_decode($conversation['source'], true);
1008                                 if (!empty($data['type'])) {
1009                                         if (in_array($data['type'], ['Create', 'Update'])) {
1010                                                 if ($object_mode) {
1011                                                         unset($data['@context']);
1012                                                         unset($data['signature']);
1013                                                 }
1014                                                 Logger::info('Return stored conversation', ['item' => $item_id]);
1015                                                 return $data;
1016                                         } elseif (in_array('as:' . $data['type'], Receiver::CONTENT_TYPES)) {
1017                                                 if (!empty($data['@context'])) {
1018                                                         $context = $data['@context'];
1019                                                         unset($data['@context']);
1020                                                 }
1021                                                 unset($data['actor']);
1022                                                 $object = $data;
1023                                         }
1024                                 }
1025                         }
1026
1027                         $type = self::getTypeOfItem($item);
1028                 }
1029
1030                 if (!$object_mode) {
1031                         $data = ['@context' => $context ?? ActivityPub::CONTEXT];
1032
1033                         if ($item['deleted'] && ($item['gravity'] == GRAVITY_ACTIVITY)) {
1034                                 $type = 'Undo';
1035                         } elseif ($item['deleted']) {
1036                                 $type = 'Delete';
1037                         }
1038                 } else {
1039                         $data = [];
1040                 }
1041
1042                 if (($item['gravity'] == GRAVITY_ACTIVITY) && ($type != 'Undo')) {
1043                         $data['id'] = $item['uri'];
1044                 } else {
1045                         $data['id'] = $item['uri'] . '/' . $type;
1046                 }
1047
1048                 $data['type'] = $type;
1049
1050                 if (($type != 'Announce') || ($item['gravity'] != GRAVITY_PARENT)) {
1051                         $data['actor'] = $item['author-link'];
1052                 } else {
1053                         $data['actor'] = $item['owner-link'];
1054                 }
1055
1056                 $data['published'] = DateTimeFormat::utc($item['created'] . '+00:00', DateTimeFormat::ATOM);
1057
1058                 $data['instrument'] = self::getService();
1059
1060                 $data = array_merge($data, self::createPermissionBlockForItem($item, false));
1061
1062                 if (in_array($data['type'], ['Create', 'Update', 'Delete'])) {
1063                         $data['object'] = $object ?? self::createNote($item);
1064                 } elseif ($data['type'] == 'Add') {
1065                         $data = self::createAddTag($item, $data);
1066                 } elseif ($data['type'] == 'Announce') {
1067                         if ($item['verb'] == ACTIVITY::ANNOUNCE) {
1068                                 $data['object'] = $item['thr-parent'];
1069                         } else {
1070                                 $data = self::createAnnounce($item, $data);
1071                         }
1072                 } elseif ($data['type'] == 'Follow') {
1073                         $data['object'] = $item['parent-uri'];
1074                 } elseif ($data['type'] == 'Undo') {
1075                         $data['object'] = self::createActivityFromItem($item_id, true);
1076                 } else {
1077                         $data['diaspora:guid'] = $item['guid'];
1078                         if (!empty($item['signed_text'])) {
1079                                 $data['diaspora:like'] = $item['signed_text'];
1080                         }
1081                         $data['object'] = $item['thr-parent'];
1082                 }
1083
1084                 if (!empty($item['contact-uid'])) {
1085                         $uid = $item['contact-uid'];
1086                 } else {
1087                         $uid = $item['uid'];
1088                 }
1089
1090                 $owner = User::getOwnerDataById($uid);
1091
1092                 Logger::info('Fetched activity', ['item' => $item_id, 'uid' => $uid]);
1093
1094                 // We don't sign if we aren't the actor. This is important for relaying content especially for forums
1095                 if (!$object_mode && !empty($owner) && ($data['actor'] == $owner['url'])) {
1096                         return LDSignature::sign($data, $owner);
1097                 } else {
1098                         return $data;
1099                 }
1100
1101                 /// @todo Create "conversation" entry
1102         }
1103
1104         /**
1105          * Creates a location entry for a given item array
1106          *
1107          * @param array $item
1108          *
1109          * @return array with location array
1110          */
1111         private static function createLocation($item)
1112         {
1113                 $location = ['type' => 'Place'];
1114
1115                 if (!empty($item['location'])) {
1116                         $location['name'] = $item['location'];
1117                 }
1118
1119                 $coord = [];
1120
1121                 if (empty($item['coord'])) {
1122                         $coord = Map::getCoordinates($item['location']);
1123                 } else {
1124                         $coords = explode(' ', $item['coord']);
1125                         if (count($coords) == 2) {
1126                                 $coord = ['lat' => $coords[0], 'lon' => $coords[1]];
1127                         }
1128                 }
1129
1130                 if (!empty($coord['lat']) && !empty($coord['lon'])) {
1131                         $location['latitude'] = $coord['lat'];
1132                         $location['longitude'] = $coord['lon'];
1133                 }
1134
1135                 return $location;
1136         }
1137
1138         /**
1139          * Returns a tag array for a given item array
1140          *
1141          * @param array $item
1142          *
1143          * @return array of tags
1144          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1145          */
1146         private static function createTagList($item)
1147         {
1148                 $tags = [];
1149
1150                 $terms = Tag::getByURIId($item['uri-id'], [Tag::HASHTAG, Tag::MENTION, Tag::IMPLICIT_MENTION, Tag::EXCLUSIVE_MENTION]);
1151                 foreach ($terms as $term) {
1152                         if ($term['type'] == Tag::HASHTAG) {
1153                                 $url = DI::baseUrl() . '/search?tag=' . urlencode($term['name']);
1154                                 $tags[] = ['type' => 'Hashtag', 'href' => $url, 'name' => '#' . $term['name']];
1155                         } else {
1156                                 $contact = Contact::getByURL($term['url'], false, ['addr']);
1157                                 if (empty($contact)) {
1158                                         continue;
1159                                 }
1160                                 if (!empty($contact['addr'])) {
1161                                         $mention = '@' . $contact['addr'];
1162                                 } else {
1163                                         $mention = '@' . $term['url'];
1164                                 }
1165
1166                                 $tags[] = ['type' => 'Mention', 'href' => $term['url'], 'name' => $mention];
1167                         }
1168                 }
1169
1170                 $announce = self::getAnnounceArray($item);
1171                 // Mention the original author upon commented reshares
1172                 if (!empty($announce['comment'])) {
1173                         $tags[] = ['type' => 'Mention', 'href' => $announce['actor']['url'], 'name' => '@' . $announce['actor']['addr']];
1174                 }
1175
1176                 return $tags;
1177         }
1178
1179         /**
1180          * Adds attachment data to the JSON document
1181          *
1182          * @param array  $item Data of the item that is to be posted
1183          * @param string $type Object type
1184          *
1185          * @return array with attachment data
1186          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1187          */
1188         private static function createAttachmentList($item, $type)
1189         {
1190                 $attachments = [];
1191
1192                 // Currently deactivated, since it creates side effects on Mastodon and Pleroma.
1193                 // It will be reactivated, once this cleared.
1194                 /*
1195                 $attach_data = BBCode::getAttachmentData($item['body']);
1196                 if (!empty($attach_data['url'])) {
1197                         $attachment = ['type' => 'Page',
1198                                 'mediaType' => 'text/html',
1199                                 'url' => $attach_data['url']];
1200
1201                         if (!empty($attach_data['title'])) {
1202                                 $attachment['name'] = $attach_data['title'];
1203                         }
1204
1205                         if (!empty($attach_data['description'])) {
1206                                 $attachment['summary'] = $attach_data['description'];
1207                         }
1208
1209                         if (!empty($attach_data['image'])) {
1210                                 $imgdata = Images::getInfoFromURLCached($attach_data['image']);
1211                                 if ($imgdata) {
1212                                         $attachment['icon'] = ['type' => 'Image',
1213                                                 'mediaType' => $imgdata['mime'],
1214                                                 'width' => $imgdata[0],
1215                                                 'height' => $imgdata[1],
1216                                                 'url' => $attach_data['image']];
1217                                 }
1218                         }
1219
1220                         $attachments[] = $attachment;
1221                 }
1222                 */
1223                 foreach (Post\Media::getByURIId($item['uri-id'], [Post\Media::DOCUMENT, Post\Media::TORRENT, Post\Media::UNKNOWN]) as $attachment) {
1224                         $attachments[] = ['type' => 'Document',
1225                                 'mediaType' => $attachment['mimetype'],
1226                                 'url' => $attachment['url'],
1227                                 'name' => $attachment['description']];
1228                 }
1229
1230                 if ($type != 'Note') {
1231                         return $attachments;
1232                 }
1233
1234                 foreach (Post\Media::getByURIId($item['uri-id'], [Post\Media::AUDIO, Post\Media::IMAGE, Post\Media::VIDEO]) as $attachment) {
1235                         $attachments[] = ['type' => 'Document',
1236                                 'mediaType' => $attachment['mimetype'],
1237                                 'url' => $attachment['url'],
1238                                 'name' => $attachment['description']];
1239                 }
1240
1241                 return $attachments;
1242         }
1243
1244         /**
1245          * Callback function to replace a Friendica style mention in a mention that is used on AP
1246          *
1247          * @param array $match Matching values for the callback
1248          * @return string Replaced mention
1249          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1250          */
1251         private static function mentionCallback($match)
1252         {
1253                 if (empty($match[1])) {
1254                         return '';
1255                 }
1256
1257                 $data = Contact::getByURL($match[1], false, ['url', 'alias', 'nick']);
1258                 if (empty($data['nick'])) {
1259                         return $match[0];
1260                 }
1261
1262                 return '[url=' . ($data['alias'] ?: $data['url']) . ']@' . $data['nick'] . '[/url]';
1263         }
1264
1265         /**
1266          * Remove image elements since they are added as attachment
1267          *
1268          * @param string $body
1269          *
1270          * @return string with removed images
1271          */
1272         private static function removePictures($body)
1273         {
1274                 // Simplify image codes
1275                 $body = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '[img]$3[/img]', $body);
1276                 $body = preg_replace("/\[img\=(.*?)\](.*?)\[\/img\]/ism", '[img]$1[/img]', $body);
1277
1278                 // Now remove local links
1279                 $body = preg_replace_callback(
1280                         '/\[url=([^\[\]]*)\]\[img\](.*)\[\/img\]\[\/url\]/Usi',
1281                         function ($match) {
1282                                 // We remove the link when it is a link to a local photo page
1283                                 if (Photo::isLocalPage($match[1])) {
1284                                         return '';
1285                                 }
1286                                 // otherwise we just return the link
1287                                 return '[url]' . $match[1] . '[/url]';
1288                         },
1289                         $body
1290                 );
1291
1292                 // Remove all pictures
1293                 $body = preg_replace("/\[img\]([^\[\]]*)\[\/img\]/Usi", '', $body);
1294
1295                 return $body;
1296         }
1297
1298         /**
1299          * Fetches the "context" value for a givem item array from the "conversation" table
1300          *
1301          * @param array $item
1302          *
1303          * @return string with context url
1304          * @throws \Exception
1305          */
1306         private static function fetchContextURLForItem($item)
1307         {
1308                 $conversation = DBA::selectFirst('conversation', ['conversation-href', 'conversation-uri'], ['item-uri' => $item['parent-uri']]);
1309                 if (DBA::isResult($conversation) && !empty($conversation['conversation-href'])) {
1310                         $context_uri = $conversation['conversation-href'];
1311                 } elseif (DBA::isResult($conversation) && !empty($conversation['conversation-uri'])) {
1312                         $context_uri = $conversation['conversation-uri'];
1313                 } else {
1314                         $context_uri = $item['parent-uri'] . '#context';
1315                 }
1316                 return $context_uri;
1317         }
1318
1319         /**
1320          * Returns if the post contains sensitive content ("nsfw")
1321          *
1322          * @param integer $uri_id
1323          *
1324          * @return boolean
1325          * @throws \Exception
1326          */
1327         private static function isSensitive($uri_id)
1328         {
1329                 return DBA::exists('tag-view', ['uri-id' => $uri_id, 'name' => 'nsfw']);
1330         }
1331
1332         /**
1333          * Creates event data
1334          *
1335          * @param array $item
1336          *
1337          * @return array with the event data
1338          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1339          */
1340         public static function createEvent($item)
1341         {
1342                 $event = [];
1343                 $event['name'] = $item['event-summary'];
1344                 $event['content'] = BBCode::convert($item['event-desc'], false, BBCode::ACTIVITYPUB);
1345                 $event['startTime'] = DateTimeFormat::utc($item['event-start'] . '+00:00', DateTimeFormat::ATOM);
1346
1347                 if (!$item['event-nofinish']) {
1348                         $event['endTime'] = DateTimeFormat::utc($item['event-finish'] . '+00:00', DateTimeFormat::ATOM);
1349                 }
1350
1351                 if (!empty($item['event-location'])) {
1352                         $item['location'] = $item['event-location'];
1353                         $event['location'] = self::createLocation($item);
1354                 }
1355
1356                 return $event;
1357         }
1358
1359         /**
1360          * Creates a note/article object array
1361          *
1362          * @param array $item
1363          *
1364          * @return array with the object data
1365          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1366          * @throws \ImagickException
1367          */
1368         public static function createNote($item)
1369         {
1370                 if (empty($item)) {
1371                         return [];
1372                 }
1373
1374                 if ($item['event-type'] == 'event') {
1375                         $type = 'Event';
1376                 } elseif (!empty($item['title'])) {
1377                         $type = 'Article';
1378                 } else {
1379                         $type = 'Note';
1380                 }
1381
1382                 if ($item['deleted']) {
1383                         $type = 'Tombstone';
1384                 }
1385
1386                 $data = [];
1387                 $data['id'] = $item['uri'];
1388                 $data['type'] = $type;
1389
1390                 if ($item['deleted']) {
1391                         return $data;
1392                 }
1393
1394                 $data['summary'] = BBCode::toPlaintext(BBCode::getAbstract($item['body'], Protocol::ACTIVITYPUB));
1395
1396                 if ($item['uri'] != $item['thr-parent']) {
1397                         $data['inReplyTo'] = $item['thr-parent'];
1398                 } else {
1399                         $data['inReplyTo'] = null;
1400                 }
1401
1402                 $data['diaspora:guid'] = $item['guid'];
1403                 $data['published'] = DateTimeFormat::utc($item['created'] . '+00:00', DateTimeFormat::ATOM);
1404
1405                 if ($item['created'] != $item['edited']) {
1406                         $data['updated'] = DateTimeFormat::utc($item['edited'] . '+00:00', DateTimeFormat::ATOM);
1407                 }
1408
1409                 $data['url'] = $item['plink'];
1410                 $data['attributedTo'] = $item['author-link'];
1411                 $data['sensitive'] = self::isSensitive($item['uri-id']);
1412                 $data['context'] = self::fetchContextURLForItem($item);
1413
1414                 if (!empty($item['title'])) {
1415                         $data['name'] = BBCode::toPlaintext($item['title'], false);
1416                 }
1417
1418                 $permission_block = self::createPermissionBlockForItem($item, false);
1419
1420                 $body = $item['body'];
1421
1422                 if ($type == 'Note') {
1423                         $body = $item['raw-body'] ?? self::removePictures($body);
1424                 } elseif (($type == 'Article') && empty($data['summary'])) {
1425                         $data['summary'] = BBCode::toPlaintext(Plaintext::shorten(self::removePictures($body), 1000));
1426                 }
1427
1428                 if (empty($item['uid']) || !Feature::isEnabled($item['uid'], 'explicit_mentions')) {
1429                         $body = self::prependMentions($body, $item['uri-id'], $item['author-link']);
1430                 }
1431
1432                 if ($type == 'Event') {
1433                         $data = array_merge($data, self::createEvent($item));
1434                 } else {
1435                         $regexp = "/[@!]\[url\=([^\[\]]*)\].*?\[\/url\]/ism";
1436                         $body = preg_replace_callback($regexp, ['self', 'mentionCallback'], $body);
1437
1438                         $data['content'] = BBCode::convert($body, false, BBCode::ACTIVITYPUB);
1439                 }
1440
1441                 // The regular "content" field does contain a minimized HTML. This is done since systems like
1442                 // Mastodon has got problems with - for example - embedded pictures.
1443                 // The contentMap does contain the unmodified HTML.
1444                 $language = self::getLanguage($item);
1445                 if (!empty($language)) {
1446                         $regexp = "/[@!]\[url\=([^\[\]]*)\].*?\[\/url\]/ism";
1447                         $richbody = preg_replace_callback($regexp, ['self', 'mentionCallback'], $item['body']);
1448                         $richbody = BBCode::removeAttachment($richbody);
1449
1450                         $data['contentMap'][$language] = BBCode::convert($richbody, false);
1451                 }
1452
1453                 $data['source'] = ['content' => $item['body'], 'mediaType' => "text/bbcode"];
1454
1455                 if (!empty($item['signed_text']) && ($item['uri'] != $item['thr-parent'])) {
1456                         $data['diaspora:comment'] = $item['signed_text'];
1457                 }
1458
1459                 $data['attachment'] = self::createAttachmentList($item, $type);
1460                 $data['tag'] = self::createTagList($item);
1461
1462                 if (empty($data['location']) && (!empty($item['coord']) || !empty($item['location']))) {
1463                         $data['location'] = self::createLocation($item);
1464                 }
1465
1466                 if (!empty($item['app'])) {
1467                         $data['generator'] = ['type' => 'Application', 'name' => $item['app']];
1468                 }
1469
1470                 $data = array_merge($data, $permission_block);
1471
1472                 return $data;
1473         }
1474
1475         /**
1476          * Fetches the language from the post, the user or the system.
1477          *
1478          * @param array $item
1479          *
1480          * @return string language string
1481          */
1482         private static function getLanguage(array $item)
1483         {
1484                 // Try to fetch the language from the post itself
1485                 if (!empty($item['language'])) {
1486                         $languages = array_keys(json_decode($item['language'], true));
1487                         if (!empty($languages[0])) {
1488                                 return $languages[0];
1489                         }
1490                 }
1491
1492                 // Otherwise use the user's language
1493                 if (!empty($item['uid'])) {
1494                         $user = DBA::selectFirst('user', ['language'], ['uid' => $item['uid']]);
1495                         if (!empty($user['language'])) {
1496                                 return $user['language'];
1497                         }
1498                 }
1499
1500                 // And finally just use the system language
1501                 return DI::config()->get('system', 'language');
1502         }
1503
1504         /**
1505          * Creates an an "add tag" entry
1506          *
1507          * @param array $item
1508          * @param array $data activity data
1509          *
1510          * @return array with activity data for adding tags
1511          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1512          * @throws \ImagickException
1513          */
1514         private static function createAddTag($item, $data)
1515         {
1516                 $object = XML::parseString($item['object']);
1517                 $target = XML::parseString($item["target"]);
1518
1519                 $data['diaspora:guid'] = $item['guid'];
1520                 $data['actor'] = $item['author-link'];
1521                 $data['target'] = (string)$target->id;
1522                 $data['summary'] = BBCode::toPlaintext($item['body']);
1523                 $data['object'] = ['id' => (string)$object->id, 'type' => 'tag', 'name' => (string)$object->title, 'content' => (string)$object->content];
1524
1525                 return $data;
1526         }
1527
1528         /**
1529          * Creates an announce object entry
1530          *
1531          * @param array $item
1532          * @param array $data activity data
1533          *
1534          * @return array with activity data
1535          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1536          * @throws \ImagickException
1537          */
1538         private static function createAnnounce($item, $data)
1539         {
1540                 $orig_body = $item['body'];
1541                 $announce = self::getAnnounceArray($item);
1542                 if (empty($announce)) {
1543                         $data['type'] = 'Create';
1544                         $data['object'] = self::createNote($item);
1545                         return $data;
1546                 }
1547
1548                 if (empty($announce['comment'])) {
1549                         // Pure announce, without a quote
1550                         $data['type'] = 'Announce';
1551                         $data['object'] = $announce['object']['uri'];
1552                         return $data;
1553                 }
1554
1555                 // Quote
1556                 $data['type'] = 'Create';
1557                 $item['body'] = $announce['comment'] . "\n" . $announce['object']['plink'];
1558                 $data['object'] = self::createNote($item);
1559
1560                 /// @todo Finally descide how to implement this in AP. This is a possible way:
1561                 $data['object']['attachment'][] = self::createNote($announce['object']);
1562
1563                 $data['object']['source']['content'] = $orig_body;
1564                 return $data;
1565         }
1566
1567         /**
1568          * Return announce related data if the item is an annunce
1569          *
1570          * @param array $item
1571          *
1572          * @return array
1573          */
1574         public static function getAnnounceArray($item)
1575         {
1576                 $reshared = Item::getShareArray($item);
1577                 if (empty($reshared['guid'])) {
1578                         return [];
1579                 }
1580
1581                 $reshared_item = Item::selectFirst([], ['guid' => $reshared['guid']]);
1582                 if (!DBA::isResult($reshared_item)) {
1583                         return [];
1584                 }
1585
1586                 if (!in_array($reshared_item['network'], [Protocol::ACTIVITYPUB, Protocol::DFRN])) {
1587                         return [];
1588                 }
1589
1590                 $profile = APContact::getByURL($reshared_item['author-link'], false);
1591                 if (empty($profile)) {
1592                         return [];
1593                 }
1594
1595                 return ['object' => $reshared_item, 'actor' => $profile, 'comment' => $reshared['comment']];
1596         }
1597
1598         /**
1599          * Checks if the provided item array is an announce
1600          *
1601          * @param array $item
1602          *
1603          * @return boolean
1604          */
1605         public static function isAnnounce($item)
1606         {
1607                 if (!empty($item['verb']) && ($item['verb'] == Activity::ANNOUNCE)) {
1608                         return true;
1609                 }
1610
1611                 $announce = self::getAnnounceArray($item);
1612                 if (empty($announce)) {
1613                         return false;
1614                 }
1615
1616                 return empty($announce['comment']);
1617         }
1618
1619         /**
1620          * Creates an activity id for a given contact id
1621          *
1622          * @param integer $cid Contact ID of target
1623          *
1624          * @return bool|string activity id
1625          */
1626         public static function activityIDFromContact($cid)
1627         {
1628                 $contact = DBA::selectFirst('contact', ['uid', 'id', 'created'], ['id' => $cid]);
1629                 if (!DBA::isResult($contact)) {
1630                         return false;
1631                 }
1632
1633                 $hash = hash('ripemd128', $contact['uid'].'-'.$contact['id'].'-'.$contact['created']);
1634                 $uuid = substr($hash, 0, 8). '-' . substr($hash, 8, 4) . '-' . substr($hash, 12, 4) . '-' . substr($hash, 16, 4) . '-' . substr($hash, 20, 12);
1635                 return DI::baseUrl() . '/activity/' . $uuid;
1636         }
1637
1638         /**
1639          * Transmits a contact suggestion to a given inbox
1640          *
1641          * @param integer $uid           User ID
1642          * @param string  $inbox         Target inbox
1643          * @param integer $suggestion_id Suggestion ID
1644          *
1645          * @return boolean was the transmission successful?
1646          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1647          */
1648         public static function sendContactSuggestion($uid, $inbox, $suggestion_id)
1649         {
1650                 $owner = User::getOwnerDataById($uid);
1651
1652                 $suggestion = DI::fsuggest()->getById($suggestion_id);
1653
1654                 $data = ['@context' => ActivityPub::CONTEXT,
1655                         'id' => DI::baseUrl() . '/activity/' . System::createGUID(),
1656                         'type' => 'Announce',
1657                         'actor' => $owner['url'],
1658                         'object' => $suggestion->url,
1659                         'content' => $suggestion->note,
1660                         'instrument' => self::getService(),
1661                         'to' => [ActivityPub::PUBLIC_COLLECTION],
1662                         'cc' => []];
1663
1664                 $signed = LDSignature::sign($data, $owner);
1665
1666                 Logger::log('Deliver profile deletion for user ' . $uid . ' to ' . $inbox . ' via ActivityPub', Logger::DEBUG);
1667                 return HTTPSignature::transmit($signed, $inbox, $uid);
1668         }
1669
1670         /**
1671          * Transmits a profile relocation to a given inbox
1672          *
1673          * @param integer $uid   User ID
1674          * @param string  $inbox Target inbox
1675          *
1676          * @return boolean was the transmission successful?
1677          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1678          */
1679         public static function sendProfileRelocation($uid, $inbox)
1680         {
1681                 $owner = User::getOwnerDataById($uid);
1682
1683                 $data = ['@context' => ActivityPub::CONTEXT,
1684                         'id' => DI::baseUrl() . '/activity/' . System::createGUID(),
1685                         'type' => 'dfrn:relocate',
1686                         'actor' => $owner['url'],
1687                         'object' => $owner['url'],
1688                         'published' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
1689                         'instrument' => self::getService(),
1690                         'to' => [ActivityPub::PUBLIC_COLLECTION],
1691                         'cc' => []];
1692
1693                 $signed = LDSignature::sign($data, $owner);
1694
1695                 Logger::log('Deliver profile relocation for user ' . $uid . ' to ' . $inbox . ' via ActivityPub', Logger::DEBUG);
1696                 return HTTPSignature::transmit($signed, $inbox, $uid);
1697         }
1698
1699         /**
1700          * Transmits a profile deletion to a given inbox
1701          *
1702          * @param integer $uid   User ID
1703          * @param string  $inbox Target inbox
1704          *
1705          * @return boolean was the transmission successful?
1706          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1707          */
1708         public static function sendProfileDeletion($uid, $inbox)
1709         {
1710                 $owner = User::getOwnerDataById($uid);
1711
1712                 if (empty($owner)) {
1713                         Logger::error('No owner data found, the deletion message cannot be processed.', ['user' => $uid]);
1714                         return false;
1715                 }
1716
1717                 if (empty($owner['uprvkey'])) {
1718                         Logger::error('No private key for owner found, the deletion message cannot be processed.', ['user' => $uid]);
1719                         return false;
1720                 }
1721
1722                 $data = ['@context' => ActivityPub::CONTEXT,
1723                         'id' => DI::baseUrl() . '/activity/' . System::createGUID(),
1724                         'type' => 'Delete',
1725                         'actor' => $owner['url'],
1726                         'object' => $owner['url'],
1727                         'published' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
1728                         'instrument' => self::getService(),
1729                         'to' => [ActivityPub::PUBLIC_COLLECTION],
1730                         'cc' => []];
1731
1732                 $signed = LDSignature::sign($data, $owner);
1733
1734                 Logger::log('Deliver profile deletion for user ' . $uid . ' to ' . $inbox . ' via ActivityPub', Logger::DEBUG);
1735                 return HTTPSignature::transmit($signed, $inbox, $uid);
1736         }
1737
1738         /**
1739          * Transmits a profile change to a given inbox
1740          *
1741          * @param integer $uid   User ID
1742          * @param string  $inbox Target inbox
1743          *
1744          * @return boolean was the transmission successful?
1745          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1746          * @throws \ImagickException
1747          */
1748         public static function sendProfileUpdate($uid, $inbox)
1749         {
1750                 $owner = User::getOwnerDataById($uid);
1751                 $profile = APContact::getByURL($owner['url']);
1752
1753                 $data = ['@context' => ActivityPub::CONTEXT,
1754                         'id' => DI::baseUrl() . '/activity/' . System::createGUID(),
1755                         'type' => 'Update',
1756                         'actor' => $owner['url'],
1757                         'object' => self::getProfile($uid),
1758                         'published' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
1759                         'instrument' => self::getService(),
1760                         'to' => [$profile['followers']],
1761                         'cc' => []];
1762
1763                 $signed = LDSignature::sign($data, $owner);
1764
1765                 Logger::log('Deliver profile update for user ' . $uid . ' to ' . $inbox . ' via ActivityPub', Logger::DEBUG);
1766                 return HTTPSignature::transmit($signed, $inbox, $uid);
1767         }
1768
1769         /**
1770          * Transmits a given activity to a target
1771          *
1772          * @param string  $activity Type name
1773          * @param string  $target   Target profile
1774          * @param integer $uid      User ID
1775          * @return bool
1776          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1777          * @throws \ImagickException
1778          * @throws \Exception
1779          */
1780         public static function sendActivity($activity, $target, $uid, $id = '')
1781         {
1782                 $profile = APContact::getByURL($target);
1783                 if (empty($profile['inbox'])) {
1784                         Logger::warning('No inbox found for target', ['target' => $target, 'profile' => $profile]);
1785                         return;
1786                 }
1787
1788                 $owner = User::getOwnerDataById($uid);
1789
1790                 if (empty($id)) {
1791                         $id = DI::baseUrl() . '/activity/' . System::createGUID();
1792                 }
1793
1794                 $data = ['@context' => ActivityPub::CONTEXT,
1795                         'id' => $id,
1796                         'type' => $activity,
1797                         'actor' => $owner['url'],
1798                         'object' => $profile['url'],
1799                         'instrument' => self::getService(),
1800                         'to' => [$profile['url']]];
1801
1802                 Logger::log('Sending activity ' . $activity . ' to ' . $target . ' for user ' . $uid, Logger::DEBUG);
1803
1804                 $signed = LDSignature::sign($data, $owner);
1805                 return HTTPSignature::transmit($signed, $profile['inbox'], $uid);
1806         }
1807
1808         /**
1809          * Transmits a "follow object" activity to a target
1810          * This is a preparation for sending automated "follow" requests when receiving "Announce" messages
1811          *
1812          * @param string  $object Object URL
1813          * @param string  $target Target profile
1814          * @param integer $uid    User ID
1815          * @return bool
1816          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1817          * @throws \ImagickException
1818          * @throws \Exception
1819          */
1820         public static function sendFollowObject($object, $target, $uid = 0)
1821         {
1822                 $profile = APContact::getByURL($target);
1823                 if (empty($profile['inbox'])) {
1824                         Logger::warning('No inbox found for target', ['target' => $target, 'profile' => $profile]);
1825                         return;
1826                 }
1827
1828                 if (empty($uid)) {
1829                         // Fetch the list of administrators
1830                         $admin_mail = explode(',', str_replace(' ', '', DI::config()->get('config', 'admin_email')));
1831
1832                         // We need to use some user as a sender. It doesn't care who it will send. We will use an administrator account.
1833                         $condition = ['verified' => true, 'blocked' => false, 'account_removed' => false, 'account_expired' => false, 'email' => $admin_mail];
1834                         $first_user = DBA::selectFirst('user', ['uid'], $condition);
1835                         $uid = $first_user['uid'];
1836                 }
1837
1838                 $condition = ['verb' => Activity::FOLLOW, 'uid' => 0, 'parent-uri' => $object,
1839                         'author-id' => Contact::getPublicIdByUserId($uid)];
1840                 if (Item::exists($condition)) {
1841                         Logger::log('Follow for ' . $object . ' for user ' . $uid . ' does already exist.', Logger::DEBUG);
1842                         return false;
1843                 }
1844
1845                 $owner = User::getOwnerDataById($uid);
1846
1847                 $data = ['@context' => ActivityPub::CONTEXT,
1848                         'id' => DI::baseUrl() . '/activity/' . System::createGUID(),
1849                         'type' => 'Follow',
1850                         'actor' => $owner['url'],
1851                         'object' => $object,
1852                         'instrument' => self::getService(),
1853                         'to' => [$profile['url']]];
1854
1855                 Logger::log('Sending follow ' . $object . ' to ' . $target . ' for user ' . $uid, Logger::DEBUG);
1856
1857                 $signed = LDSignature::sign($data, $owner);
1858                 return HTTPSignature::transmit($signed, $profile['inbox'], $uid);
1859         }
1860
1861         /**
1862          * Transmit a message that the contact request had been accepted
1863          *
1864          * @param string  $target Target profile
1865          * @param         $id
1866          * @param integer $uid    User ID
1867          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1868          * @throws \ImagickException
1869          */
1870         public static function sendContactAccept($target, $id, $uid)
1871         {
1872                 $profile = APContact::getByURL($target);
1873                 if (empty($profile['inbox'])) {
1874                         Logger::warning('No inbox found for target', ['target' => $target, 'profile' => $profile]);
1875                         return;
1876                 }
1877
1878                 $owner = User::getOwnerDataById($uid);
1879                 $data = ['@context' => ActivityPub::CONTEXT,
1880                         'id' => DI::baseUrl() . '/activity/' . System::createGUID(),
1881                         'type' => 'Accept',
1882                         'actor' => $owner['url'],
1883                         'object' => [
1884                                 'id' => (string)$id,
1885                                 'type' => 'Follow',
1886                                 'actor' => $profile['url'],
1887                                 'object' => $owner['url']
1888                         ],
1889                         'instrument' => self::getService(),
1890                         'to' => [$profile['url']]];
1891
1892                 Logger::debug('Sending accept to ' . $target . ' for user ' . $uid . ' with id ' . $id);
1893
1894                 $signed = LDSignature::sign($data, $owner);
1895                 HTTPSignature::transmit($signed, $profile['inbox'], $uid);
1896         }
1897
1898         /**
1899          * Reject a contact request or terminates the contact relation
1900          *
1901          * @param string  $target Target profile
1902          * @param         $id
1903          * @param integer $uid    User ID
1904          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1905          * @throws \ImagickException
1906          */
1907         public static function sendContactReject($target, $id, $uid)
1908         {
1909                 $profile = APContact::getByURL($target);
1910                 if (empty($profile['inbox'])) {
1911                         Logger::warning('No inbox found for target', ['target' => $target, 'profile' => $profile]);
1912                         return;
1913                 }
1914
1915                 $owner = User::getOwnerDataById($uid);
1916                 $data = ['@context' => ActivityPub::CONTEXT,
1917                         'id' => DI::baseUrl() . '/activity/' . System::createGUID(),
1918                         'type' => 'Reject',
1919                         'actor' => $owner['url'],
1920                         'object' => [
1921                                 'id' => (string)$id,
1922                                 'type' => 'Follow',
1923                                 'actor' => $profile['url'],
1924                                 'object' => $owner['url']
1925                         ],
1926                         'instrument' => self::getService(),
1927                         'to' => [$profile['url']]];
1928
1929                 Logger::debug('Sending reject to ' . $target . ' for user ' . $uid . ' with id ' . $id);
1930
1931                 $signed = LDSignature::sign($data, $owner);
1932                 HTTPSignature::transmit($signed, $profile['inbox'], $uid);
1933         }
1934
1935         /**
1936          * Transmits a message that we don't want to follow this contact anymore
1937          *
1938          * @param string  $target Target profile
1939          * @param integer $uid    User ID
1940          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1941          * @throws \ImagickException
1942          * @throws \Exception
1943          * @return bool success
1944          */
1945         public static function sendContactUndo($target, $cid, $uid)
1946         {
1947                 $profile = APContact::getByURL($target);
1948                 if (empty($profile['inbox'])) {
1949                         Logger::warning('No inbox found for target', ['target' => $target, 'profile' => $profile]);
1950                         return false;
1951                 }
1952
1953                 $object_id = self::activityIDFromContact($cid);
1954                 if (empty($object_id)) {
1955                         return false;
1956                 }
1957
1958                 $id = DI::baseUrl() . '/activity/' . System::createGUID();
1959
1960                 $owner = User::getOwnerDataById($uid);
1961                 $data = ['@context' => ActivityPub::CONTEXT,
1962                         'id' => $id,
1963                         'type' => 'Undo',
1964                         'actor' => $owner['url'],
1965                         'object' => ['id' => $object_id, 'type' => 'Follow',
1966                                 'actor' => $owner['url'],
1967                                 'object' => $profile['url']],
1968                         'instrument' => self::getService(),
1969                         'to' => [$profile['url']]];
1970
1971                 Logger::log('Sending undo to ' . $target . ' for user ' . $uid . ' with id ' . $id, Logger::DEBUG);
1972
1973                 $signed = LDSignature::sign($data, $owner);
1974                 return HTTPSignature::transmit($signed, $profile['inbox'], $uid);
1975         }
1976
1977         private static function prependMentions($body, int $uriid, string $authorLink)
1978         {
1979                 $mentions = [];
1980
1981                 foreach (Tag::getByURIId($uriid, [Tag::IMPLICIT_MENTION]) as $tag) {
1982                         $profile = Contact::getByURL($tag['url'], false, ['addr', 'contact-type', 'nick']);
1983                         if (!empty($profile['addr'])
1984                                 && $profile['contact-type'] != Contact::TYPE_COMMUNITY
1985                                 && !strstr($body, $profile['addr'])
1986                                 && !strstr($body, $tag['url'])
1987                                 && $tag['url'] !== $authorLink
1988                         ) {
1989                                 $mentions[] = '@[url=' . $tag['url'] . ']' . $profile['nick'] . '[/url]';
1990                         }
1991                 }
1992
1993                 $mentions[] = $body;
1994
1995                 return implode(' ', $mentions);
1996         }
1997 }