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