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