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