]> git.mxchange.org Git - friendica.git/blob - src/Protocol/ActivityPub/Transmitter.php
Merge pull request #6508 from nupplaphil/logger_enh
[friendica.git] / src / Protocol / ActivityPub / Transmitter.php
1 <?php
2 /**
3  * @file src/Protocol/ActivityPub/Transmitter.php
4  */
5 namespace Friendica\Protocol\ActivityPub;
6
7 use Friendica\BaseObject;
8 use Friendica\Database\DBA;
9 use Friendica\Core\Logger;
10 use Friendica\Core\System;
11 use Friendica\Util\HTTPSignature;
12 use Friendica\Core\Protocol;
13 use Friendica\Model\Conversation;
14 use Friendica\Model\Contact;
15 use Friendica\Model\APContact;
16 use Friendica\Model\Item;
17 use Friendica\Model\Term;
18 use Friendica\Model\User;
19 use Friendica\Util\DateTimeFormat;
20 use Friendica\Content\Text\BBCode;
21 use Friendica\Util\JsonLD;
22 use Friendica\Util\LDSignature;
23 use Friendica\Model\Profile;
24 use Friendica\Object\Image;
25 use Friendica\Protocol\ActivityPub;
26 use Friendica\Core\Cache;
27 use Friendica\Util\Map;
28 use Friendica\Util\Network;
29
30 require_once 'include/api.php';
31
32 /**
33  * @brief ActivityPub Transmitter Protocol class
34  *
35  * To-Do:
36  * - Undo Announce
37  */
38 class Transmitter
39 {
40         /**
41          * collects the lost of followers of the given owner
42          *
43          * @param array   $owner Owner array
44          * @param integer $page  Page number
45          *
46          * @return array of owners
47          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
48          */
49         public static function getFollowers($owner, $page = null)
50         {
51                 $condition = ['rel' => [Contact::FOLLOWER, Contact::FRIEND], 'network' => Protocol::NATIVE_SUPPORT, 'uid' => $owner['uid'],
52                         'self' => false, 'deleted' => false, 'hidden' => false, 'archive' => false, 'pending' => false];
53                 $count = DBA::count('contact', $condition);
54
55                 $data = ['@context' => ActivityPub::CONTEXT];
56                 $data['id'] = System::baseUrl() . '/followers/' . $owner['nickname'];
57                 $data['type'] = 'OrderedCollection';
58                 $data['totalItems'] = $count;
59
60                 // When we hide our friends we will only show the pure number but don't allow more.
61                 $profile = Profile::getByUID($owner['uid']);
62                 if (!empty($profile['hide-friends'])) {
63                         return $data;
64                 }
65
66                 if (empty($page)) {
67                         $data['first'] = System::baseUrl() . '/followers/' . $owner['nickname'] . '?page=1';
68                 } else {
69                         $list = [];
70
71                         $contacts = DBA::select('contact', ['url'], $condition, ['limit' => [($page - 1) * 100, 100]]);
72                         while ($contact = DBA::fetch($contacts)) {
73                                 $list[] = $contact['url'];
74                         }
75
76                         if (!empty($list)) {
77                                 $data['next'] = System::baseUrl() . '/followers/' . $owner['nickname'] . '?page=' . ($page + 1);
78                         }
79
80                         $data['partOf'] = System::baseUrl() . '/followers/' . $owner['nickname'];
81
82                         $data['orderedItems'] = $list;
83                 }
84
85                 return $data;
86         }
87
88         /**
89          * Create list of following contacts
90          *
91          * @param array   $owner Owner array
92          * @param integer $page  Page numbe
93          *
94          * @return array of following contacts
95          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
96          */
97         public static function getFollowing($owner, $page = null)
98         {
99                 $condition = ['rel' => [Contact::SHARING, Contact::FRIEND], 'network' => Protocol::NATIVE_SUPPORT, 'uid' => $owner['uid'],
100                         'self' => false, 'deleted' => false, 'hidden' => false, 'archive' => false, 'pending' => false];
101                 $count = DBA::count('contact', $condition);
102
103                 $data = ['@context' => ActivityPub::CONTEXT];
104                 $data['id'] = System::baseUrl() . '/following/' . $owner['nickname'];
105                 $data['type'] = 'OrderedCollection';
106                 $data['totalItems'] = $count;
107
108                 // When we hide our friends we will only show the pure number but don't allow more.
109                 $profile = Profile::getByUID($owner['uid']);
110                 if (!empty($profile['hide-friends'])) {
111                         return $data;
112                 }
113
114                 if (empty($page)) {
115                         $data['first'] = System::baseUrl() . '/following/' . $owner['nickname'] . '?page=1';
116                 } else {
117                         $list = [];
118
119                         $contacts = DBA::select('contact', ['url'], $condition, ['limit' => [($page - 1) * 100, 100]]);
120                         while ($contact = DBA::fetch($contacts)) {
121                                 $list[] = $contact['url'];
122                         }
123
124                         if (!empty($list)) {
125                                 $data['next'] = System::baseUrl() . '/following/' . $owner['nickname'] . '?page=' . ($page + 1);
126                         }
127
128                         $data['partOf'] = System::baseUrl() . '/following/' . $owner['nickname'];
129
130                         $data['orderedItems'] = $list;
131                 }
132
133                 return $data;
134         }
135
136         /**
137          * Public posts for the given owner
138          *
139          * @param array   $owner Owner array
140          * @param integer $page  Page numbe
141          *
142          * @return array of posts
143          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
144          * @throws \ImagickException
145          */
146         public static function getOutbox($owner, $page = null)
147         {
148                 $public_contact = Contact::getIdForURL($owner['url'], 0, true);
149
150                 $condition = ['uid' => 0, 'contact-id' => $public_contact, 'author-id' => $public_contact,
151                         'private' => false, 'gravity' => [GRAVITY_PARENT, GRAVITY_COMMENT],
152                         'deleted' => false, 'visible' => true];
153                 $count = DBA::count('item', $condition);
154
155                 $data = ['@context' => ActivityPub::CONTEXT];
156                 $data['id'] = System::baseUrl() . '/outbox/' . $owner['nickname'];
157                 $data['type'] = 'OrderedCollection';
158                 $data['totalItems'] = $count;
159
160                 if (empty($page)) {
161                         $data['first'] = System::baseUrl() . '/outbox/' . $owner['nickname'] . '?page=1';
162                 } else {
163                         $list = [];
164
165                         $condition['parent-network'] = Protocol::NATIVE_SUPPORT;
166
167                         $items = Item::select(['id'], $condition, ['limit' => [($page - 1) * 20, 20], 'order' => ['created' => true]]);
168                         while ($item = Item::fetch($items)) {
169                                 $object = self::createObjectFromItemID($item['id']);
170                                 unset($object['@context']);
171                                 $list[] = $object;
172                         }
173
174                         if (!empty($list)) {
175                                 $data['next'] = System::baseUrl() . '/outbox/' . $owner['nickname'] . '?page=' . ($page + 1);
176                         }
177
178                         $data['partOf'] = System::baseUrl() . '/outbox/' . $owner['nickname'];
179
180                         $data['orderedItems'] = $list;
181                 }
182
183                 return $data;
184         }
185
186         /**
187          * Return the ActivityPub profile of the given user
188          *
189          * @param integer $uid User ID
190          * @return array with profile data
191          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
192          */
193         public static function getProfile($uid)
194         {
195                 $condition = ['uid' => $uid, 'blocked' => false, 'account_expired' => false,
196                         'account_removed' => false, 'verified' => true];
197                 $fields = ['guid', 'nickname', 'pubkey', 'account-type', 'page-flags'];
198                 $user = DBA::selectFirst('user', $fields, $condition);
199                 if (!DBA::isResult($user)) {
200                         return [];
201                 }
202
203                 $fields = ['locality', 'region', 'country-name'];
204                 $profile = DBA::selectFirst('profile', $fields, ['uid' => $uid, 'is-default' => true]);
205                 if (!DBA::isResult($profile)) {
206                         return [];
207                 }
208
209                 $fields = ['name', 'url', 'location', 'about', 'avatar', 'photo'];
210                 $contact = DBA::selectFirst('contact', $fields, ['uid' => $uid, 'self' => true]);
211                 if (!DBA::isResult($contact)) {
212                         return [];
213                 }
214
215                 // On old installations and never changed contacts this might not be filled
216                 if (empty($contact['avatar'])) {
217                         $contact['avatar'] = $contact['photo'];
218                 }
219
220                 $data = ['@context' => ActivityPub::CONTEXT];
221                 $data['id'] = $contact['url'];
222                 $data['diaspora:guid'] = $user['guid'];
223                 $data['type'] = ActivityPub::ACCOUNT_TYPES[$user['account-type']];
224                 $data['following'] = System::baseUrl() . '/following/' . $user['nickname'];
225                 $data['followers'] = System::baseUrl() . '/followers/' . $user['nickname'];
226                 $data['inbox'] = System::baseUrl() . '/inbox/' . $user['nickname'];
227                 $data['outbox'] = System::baseUrl() . '/outbox/' . $user['nickname'];
228                 $data['preferredUsername'] = $user['nickname'];
229                 $data['name'] = $contact['name'];
230                 $data['vcard:hasAddress'] = ['@type' => 'vcard:Home', 'vcard:country-name' => $profile['country-name'],
231                         'vcard:region' => $profile['region'], 'vcard:locality' => $profile['locality']];
232                 $data['summary'] = $contact['about'];
233                 $data['url'] = $contact['url'];
234                 $data['manuallyApprovesFollowers'] = in_array($user['page-flags'], [User::PAGE_FLAGS_NORMAL, User::PAGE_FLAGS_PRVGROUP]);
235                 $data['publicKey'] = ['id' => $contact['url'] . '#main-key',
236                         'owner' => $contact['url'],
237                         'publicKeyPem' => $user['pubkey']];
238                 $data['endpoints'] = ['sharedInbox' => System::baseUrl() . '/inbox'];
239                 $data['icon'] = ['type' => 'Image',
240                         'url' => $contact['avatar']];
241
242                 // tags: https://kitty.town/@inmysocks/100656097926961126.json
243                 return $data;
244         }
245
246         /**
247          * Returns an array with permissions of a given item array
248          *
249          * @param array $item
250          *
251          * @return array with permissions
252          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
253          * @throws \ImagickException
254          */
255         private static function fetchPermissionBlockFromConversation($item)
256         {
257                 if (empty($item['thr-parent'])) {
258                         return [];
259                 }
260
261                 $condition = ['item-uri' => $item['thr-parent'], 'protocol' => Conversation::PARCEL_ACTIVITYPUB];
262                 $conversation = DBA::selectFirst('conversation', ['source'], $condition);
263                 if (!DBA::isResult($conversation)) {
264                         return [];
265                 }
266
267                 $activity = json_decode($conversation['source'], true);
268
269                 $actor = JsonLD::fetchElement($activity, 'actor', 'id');
270                 $profile = APContact::getByURL($actor);
271
272                 $item_profile = APContact::getByURL($item['author-link']);
273                 $exclude[] = $item['author-link'];
274
275                 if ($item['gravity'] == GRAVITY_PARENT) {
276                         $exclude[] = $item['owner-link'];
277                 }
278
279                 $permissions['to'][] = $actor;
280
281                 foreach (['to', 'cc', 'bto', 'bcc'] as $element) {
282                         if (empty($activity[$element])) {
283                                 continue;
284                         }
285                         if (is_string($activity[$element])) {
286                                 $activity[$element] = [$activity[$element]];
287                         }
288
289                         foreach ($activity[$element] as $receiver) {
290                                 if ($receiver == $profile['followers'] && !empty($item_profile['followers'])) {
291                                         $permissions[$element][] = $item_profile['followers'];
292                                 } elseif (!in_array($receiver, $exclude)) {
293                                         $permissions[$element][] = $receiver;
294                                 }
295                         }
296                 }
297                 return $permissions;
298         }
299
300         /**
301          * Creates an array of permissions from an item thread
302          *
303          * @param array   $item
304          * @param boolean $blindcopy
305          * @param boolean $last_id
306          *
307          * @return array with permission data
308          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
309          * @throws \ImagickException
310          */
311         private static function createPermissionBlockForItem($item, $blindcopy, $last_id = 0)
312         {
313                 if ($last_id == 0) {
314                         $last_id = $item['id'];
315                 }
316
317                 $always_bcc = false;
318
319                 // Check if we should always deliver our stuff via BCC
320                 if (!empty($item['uid'])) {
321                         $profile = Profile::getByUID($item['uid']);
322                         if (!empty($profile)) {
323                                 $always_bcc = $profile['hide-friends'];
324                         }
325                 }
326
327                 // Will be activated in a later step
328                 // $networks = [Protocol::ACTIVITYPUB, Protocol::DFRN, Protocol::DIASPORA, Protocol::OSTATUS];
329
330                 // For now only send to these contacts:
331                 $networks = [Protocol::ACTIVITYPUB, Protocol::OSTATUS];
332
333                 $data = ['to' => [], 'cc' => [], 'bcc' => []];
334
335                 $actor_profile = APContact::getByURL($item['author-link']);
336
337                 $terms = Term::tagArrayFromItemId($item['id'], TERM_MENTION);
338
339                 if (!$item['private']) {
340                         $data = array_merge($data, self::fetchPermissionBlockFromConversation($item));
341
342                         $data['to'][] = ActivityPub::PUBLIC_COLLECTION;
343                         if (!empty($actor_profile['followers'])) {
344                                 $data['cc'][] = $actor_profile['followers'];
345                         }
346
347                         foreach ($terms as $term) {
348                                 $profile = APContact::getByURL($term['url'], false);
349                                 if (!empty($profile)) {
350                                         $data['to'][] = $profile['url'];
351                                 }
352                         }
353                 } else {
354                         $receiver_list = Item::enumeratePermissions($item);
355
356                         foreach ($terms as $term) {
357                                 $cid = Contact::getIdForURL($term['url'], $item['uid']);
358                                 if (!empty($cid) && in_array($cid, $receiver_list)) {
359                                         $contact = DBA::selectFirst('contact', ['url'], ['id' => $cid, 'network' => $networks]);
360                                         if (DBA::isResult($contact) && !empty($profile = APContact::getByURL($contact['url'], false))) {
361                                                 $data['to'][] = $profile['url'];
362                                         }
363                                 }
364                         }
365
366                         foreach ($receiver_list as $receiver) {
367                                 $contact = DBA::selectFirst('contact', ['url', 'hidden'], ['id' => $receiver, 'network' => $networks]);
368                                 if (DBA::isResult($contact) && !empty($profile = APContact::getByURL($contact['url'], false))) {
369                                         if ($contact['hidden'] || $always_bcc) {
370                                                 $data['bcc'][] = $profile['url'];
371                                         } else {
372                                                 $data['cc'][] = $profile['url'];
373                                         }
374                                 }
375                         }
376                 }
377
378                 $parents = Item::select(['id', 'author-link', 'owner-link', 'gravity', 'uri'], ['parent' => $item['parent']]);
379                 while ($parent = Item::fetch($parents)) {
380                         // Don't include data from future posts
381                         if ($parent['id'] >= $last_id) {
382                                 continue;
383                         }
384
385                         $profile = APContact::getByURL($parent['author-link'], false);
386                         if (!empty($profile)) {
387                                 if ($parent['uri'] == $item['thr-parent']) {
388                                         $data['to'][] = $profile['url'];
389                                 } else {
390                                         $data['cc'][] = $profile['url'];
391                                 }
392                         }
393
394                         if ($item['gravity'] != GRAVITY_PARENT) {
395                                 continue;
396                         }
397
398                         $profile = APContact::getByURL($parent['owner-link'], false);
399                         if (!empty($profile)) {
400                                 $data['cc'][] = $profile['url'];
401                         }
402                 }
403                 DBA::close($parents);
404
405                 $data['to'] = array_unique($data['to']);
406                 $data['cc'] = array_unique($data['cc']);
407                 $data['bcc'] = array_unique($data['bcc']);
408
409                 if (($key = array_search($item['author-link'], $data['to'])) !== false) {
410                         unset($data['to'][$key]);
411                 }
412
413                 if (($key = array_search($item['author-link'], $data['cc'])) !== false) {
414                         unset($data['cc'][$key]);
415                 }
416
417                 if (($key = array_search($item['author-link'], $data['bcc'])) !== false) {
418                         unset($data['bcc'][$key]);
419                 }
420
421                 foreach ($data['to'] as $to) {
422                         if (($key = array_search($to, $data['cc'])) !== false) {
423                                 unset($data['cc'][$key]);
424                         }
425
426                         if (($key = array_search($to, $data['bcc'])) !== false) {
427                                 unset($data['bcc'][$key]);
428                         }
429                 }
430
431                 foreach ($data['cc'] as $cc) {
432                         if (($key = array_search($cc, $data['bcc'])) !== false) {
433                                 unset($data['bcc'][$key]);
434                         }
435                 }
436
437                 $receivers = ['to' => array_values($data['to']), 'cc' => array_values($data['cc']), 'bcc' => array_values($data['bcc'])];
438
439                 if (!$blindcopy) {
440                         unset($receivers['bcc']);
441                 }
442
443                 return $receivers;
444         }
445
446         /**
447          * Fetches a list of inboxes of followers of a given user
448          *
449          * @param integer $uid      User ID
450          * @param boolean $personal fetch personal inboxes
451          *
452          * @return array of follower inboxes
453          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
454          * @throws \ImagickException
455          */
456         public static function fetchTargetInboxesforUser($uid, $personal = false)
457         {
458                 $inboxes = [];
459
460                 // Will be activated in a later step
461                 // $networks = [Protocol::ACTIVITYPUB, Protocol::DFRN, Protocol::DIASPORA, Protocol::OSTATUS];
462
463                 // For now only send to these contacts:
464                 $networks = [Protocol::ACTIVITYPUB, Protocol::OSTATUS];
465
466                 $condition = ['uid' => $uid, 'network' => $networks, 'archive' => false, 'pending' => false];
467
468                 if (!empty($uid)) {
469                         $condition['rel'] = [Contact::FOLLOWER, Contact::FRIEND];
470                 }
471
472                 $contacts = DBA::select('contact', ['url'], $condition);
473                 while ($contact = DBA::fetch($contacts)) {
474                         if (Network::isUrlBlocked($contact['url'])) {
475                                 continue;
476                         }
477
478                         $profile = APContact::getByURL($contact['url'], false);
479                         if (!empty($profile)) {
480                                 if (empty($profile['sharedinbox']) || $personal) {
481                                         $target = $profile['inbox'];
482                                 } else {
483                                         $target = $profile['sharedinbox'];
484                                 }
485                                 $inboxes[$target] = $target;
486                         }
487                 }
488                 DBA::close($contacts);
489
490                 return $inboxes;
491         }
492
493         /**
494          * Fetches an array of inboxes for the given item and user
495          *
496          * @param array   $item
497          * @param integer $uid      User ID
498          * @param boolean $personal fetch personal inboxes
499          * @param integer $last_id Last item id for adding receivers
500          *
501          * @return array with inboxes
502          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
503          * @throws \ImagickException
504          */
505         public static function fetchTargetInboxes($item, $uid, $personal = false, $last_id = 0)
506         {
507                 $permissions = self::createPermissionBlockForItem($item, true, $last_id);
508                 if (empty($permissions)) {
509                         return [];
510                 }
511
512                 $inboxes = [];
513
514                 if ($item['gravity'] == GRAVITY_ACTIVITY) {
515                         $item_profile = APContact::getByURL($item['author-link'], false);
516                 } else {
517                         $item_profile = APContact::getByURL($item['owner-link'], false);
518                 }
519
520                 foreach (['to', 'cc', 'bto', 'bcc'] as $element) {
521                         if (empty($permissions[$element])) {
522                                 continue;
523                         }
524
525                         $blindcopy = in_array($element, ['bto', 'bcc']);
526
527                         foreach ($permissions[$element] as $receiver) {
528                                 if (Network::isUrlBlocked($receiver)) {
529                                         continue;
530                                 }
531
532                                 if ($receiver == $item_profile['followers']) {
533                                         $inboxes = array_merge($inboxes, self::fetchTargetInboxesforUser($uid, $personal));
534                                 } else {
535                                         $profile = APContact::getByURL($receiver, false);
536                                         if (!empty($profile)) {
537                                                 if (empty($profile['sharedinbox']) || $personal || $blindcopy) {
538                                                         $target = $profile['inbox'];
539                                                 } else {
540                                                         $target = $profile['sharedinbox'];
541                                                 }
542                                                 $inboxes[$target] = $target;
543                                         }
544                                 }
545                         }
546                 }
547
548                 return $inboxes;
549         }
550
551         /**
552          * Returns the activity type of a given item
553          *
554          * @param array $item
555          *
556          * @return string with activity type
557          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
558          * @throws \ImagickException
559          */
560         private static function getTypeOfItem($item)
561         {
562                 $reshared = false;
563
564                 // Only check for a reshare, if it is a real reshare and no quoted reshare
565                 if (strpos($item['body'], "[share") === 0) {
566                         $announce = api_share_as_retweet($item);
567                         $reshared = !empty($announce['plink']);
568                 }
569
570                 if ($reshared) {
571                         $type = 'Announce';
572                 } elseif ($item['verb'] == ACTIVITY_POST) {
573                         if ($item['created'] == $item['edited']) {
574                                 $type = 'Create';
575                         } else {
576                                 $type = 'Update';
577                         }
578                 } elseif ($item['verb'] == ACTIVITY_LIKE) {
579                         $type = 'Like';
580                 } elseif ($item['verb'] == ACTIVITY_DISLIKE) {
581                         $type = 'Dislike';
582                 } elseif ($item['verb'] == ACTIVITY_ATTEND) {
583                         $type = 'Accept';
584                 } elseif ($item['verb'] == ACTIVITY_ATTENDNO) {
585                         $type = 'Reject';
586                 } elseif ($item['verb'] == ACTIVITY_ATTENDMAYBE) {
587                         $type = 'TentativeAccept';
588                 } else {
589                         $type = '';
590                 }
591
592                 return $type;
593         }
594
595         /**
596          * Creates the activity or fetches it from the cache
597          *
598          * @param integer $item_id
599          * @param boolean $force Force new cache entry
600          *
601          * @return array with the activity
602          * @throws \Exception
603          */
604         public static function createCachedActivityFromItem($item_id, $force = false)
605         {
606                 $cachekey = 'APDelivery:createActivity:' . $item_id;
607
608                 if (!$force) {
609                         $data = Cache::get($cachekey);
610                         if (!is_null($data)) {
611                                 return $data;
612                         }
613                 }
614
615                 $data = ActivityPub\Transmitter::createActivityFromItem($item_id);
616
617                 Cache::set($cachekey, $data, Cache::QUARTER_HOUR);
618                 return $data;
619         }
620
621         /**
622          * Creates an activity array for a given item id
623          *
624          * @param integer $item_id
625          * @param boolean $object_mode Is the activity item is used inside another object?
626          *
627          * @return array of activity
628          * @throws \Exception
629          */
630         public static function createActivityFromItem($item_id, $object_mode = false)
631         {
632                 $item = Item::selectFirst([], ['id' => $item_id, 'parent-network' => Protocol::NATIVE_SUPPORT]);
633
634                 if (!DBA::isResult($item)) {
635                         return false;
636                 }
637
638                 $condition = ['item-uri' => $item['uri'], 'protocol' => Conversation::PARCEL_ACTIVITYPUB];
639                 $conversation = DBA::selectFirst('conversation', ['source'], $condition);
640                 if (DBA::isResult($conversation)) {
641                         $data = json_decode($conversation['source']);
642                         if (!empty($data)) {
643                                 return $data;
644                         }
645                 }
646
647                 $type = self::getTypeOfItem($item);
648
649                 if (!$object_mode) {
650                         $data = ['@context' => ActivityPub::CONTEXT];
651
652                         if ($item['deleted'] && ($item['gravity'] == GRAVITY_ACTIVITY)) {
653                                 $type = 'Undo';
654                         } elseif ($item['deleted']) {
655                                 $type = 'Delete';
656                         }
657                 } else {
658                         $data = [];
659                 }
660
661                 $data['id'] = $item['uri'] . '#' . $type;
662                 $data['type'] = $type;
663                 $data['actor'] = $item['owner-link'];
664
665                 $data['published'] = DateTimeFormat::utc($item['created'] . '+00:00', DateTimeFormat::ATOM);
666
667                 $data['instrument'] = ['type' => 'Service', 'name' => BaseObject::getApp()->getUserAgent()];
668
669                 $data = array_merge($data, self::createPermissionBlockForItem($item, false));
670
671                 if (in_array($data['type'], ['Create', 'Update', 'Delete'])) {
672                         $data['object'] = self::createNote($item);
673                 } elseif ($data['type'] == 'Announce') {
674                         $data['object'] = self::createAnnounce($item);
675                 } elseif ($data['type'] == 'Undo') {
676                         $data['object'] = self::createActivityFromItem($item_id, true);
677                 } else {
678                         $data['diaspora:guid'] = $item['guid'];
679                         if (!empty($item['signed_text'])) {
680                                 $data['diaspora:like'] = $item['signed_text'];
681                         }
682                         $data['object'] = $item['thr-parent'];
683                 }
684
685                 if (!empty($item['contact-uid'])) {
686                         $uid = $item['contact-uid'];
687                 } else {
688                         $uid = $item['uid'];
689                 }
690
691                 $owner = User::getOwnerDataById($uid);
692
693                 if (!$object_mode && !empty($owner)) {
694                         return LDSignature::sign($data, $owner);
695                 } else {
696                         return $data;
697                 }
698
699                 /// @todo Create "conversation" entry
700         }
701
702         /**
703          * Creates an object array for a given item id
704          *
705          * @param integer $item_id
706          *
707          * @return array with the object data
708          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
709          * @throws \ImagickException
710          */
711         public static function createObjectFromItemID($item_id)
712         {
713                 $item = Item::selectFirst([], ['id' => $item_id, 'parent-network' => Protocol::NATIVE_SUPPORT]);
714
715                 if (!DBA::isResult($item)) {
716                         return false;
717                 }
718
719                 $data = ['@context' => ActivityPub::CONTEXT];
720                 $data = array_merge($data, self::createNote($item));
721
722                 return $data;
723         }
724
725         /**
726          * Creates a location entry for a given item array
727          *
728          * @param array $item
729          *
730          * @return array with location array
731          */
732         private static function createLocation($item)
733         {
734                 $location = ['type' => 'Place'];
735
736                 if (!empty($item['location'])) {
737                         $location['name'] = $item['location'];
738                 }
739
740                 $coord = [];
741
742                 if (empty($item['coord'])) {
743                         $coord = Map::getCoordinates($item['location']);
744                 } else {
745                         $coords = explode(' ', $item['coord']);
746                         if (count($coords) == 2) {
747                                 $coord = ['lat' => $coords[0], 'lon' => $coords[1]];
748                         }
749                 }
750
751                 if (!empty($coord['lat']) && !empty($coord['lon'])) {
752                         $location['latitude'] = $coord['lat'];
753                         $location['longitude'] = $coord['lon'];
754                 }
755
756                 return $location;
757         }
758
759         /**
760          * Returns a tag array for a given item array
761          *
762          * @param array $item
763          *
764          * @return array of tags
765          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
766          */
767         private static function createTagList($item)
768         {
769                 $tags = [];
770
771                 $terms = Term::tagArrayFromItemId($item['id']);
772                 foreach ($terms as $term) {
773                         if ($term['type'] == TERM_HASHTAG) {
774                                 $url = System::baseUrl() . '/search?tag=' . urlencode($term['term']);
775                                 $tags[] = ['type' => 'Hashtag', 'href' => $url, 'name' => '#' . $term['term']];
776                         } elseif ($term['type'] == TERM_MENTION) {
777                                 $contact = Contact::getDetailsByURL($term['url']);
778                                 if (!empty($contact['addr'])) {
779                                         $mention = '@' . $contact['addr'];
780                                 } else {
781                                         $mention = '@' . $term['url'];
782                                 }
783
784                                 $tags[] = ['type' => 'Mention', 'href' => $term['url'], 'name' => $mention];
785                         }
786                 }
787                 return $tags;
788         }
789
790         /**
791          * Adds attachment data to the JSON document
792          *
793          * @param array  $item Data of the item that is to be posted
794          * @param string $type Object type
795          *
796          * @return array with attachment data
797          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
798          */
799         private static function createAttachmentList($item, $type)
800         {
801                 $attachments = [];
802
803                 $arr = explode('[/attach],', $item['attach']);
804                 if (count($arr)) {
805                         foreach ($arr as $r) {
806                                 $matches = false;
807                                 $cnt = preg_match('|\[attach\]href=\"(.*?)\" length=\"(.*?)\" type=\"(.*?)\" title=\"(.*?)\"|', $r, $matches);
808                                 if ($cnt) {
809                                         $attributes = ['type' => 'Document',
810                                                         'mediaType' => $matches[3],
811                                                         'url' => $matches[1],
812                                                         'name' => null];
813
814                                         if (trim($matches[4]) != '') {
815                                                 $attributes['name'] = trim($matches[4]);
816                                         }
817
818                                         $attachments[] = $attributes;
819                                 }
820                         }
821                 }
822
823                 if ($type != 'Note') {
824                         return $attachments;
825                 }
826
827                 // Simplify image codes
828                 $body = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '[img]$3[/img]', $item['body']);
829
830                 // Grab all pictures and create attachments out of them
831                 if (preg_match_all("/\[img\]([^\[\]]*)\[\/img\]/Usi", $body, $pictures)) {
832                         foreach ($pictures[1] as $picture) {
833                                 $imgdata = Image::getInfoFromURL($picture);
834                                 if ($imgdata) {
835                                         $attachments[] = ['type' => 'Document',
836                                                 'mediaType' => $imgdata['mime'],
837                                                 'url' => $picture,
838                                                 'name' => null];
839                                 }
840                         }
841                 }
842
843                 return $attachments;
844         }
845
846         /**
847          * @brief Callback function to replace a Friendica style mention in a mention that is used on AP
848          *
849          * @param array $match Matching values for the callback
850          * @return string Replaced mention
851          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
852          */
853         private static function mentionCallback($match)
854         {
855                 if (empty($match[1])) {
856                         return;
857                 }
858
859                 $data = Contact::getDetailsByURL($match[1]);
860                 if (empty($data) || empty($data['nick'])) {
861                         return;
862                 }
863
864                 return '@[url=' . $data['url'] . ']' . $data['nick'] . '[/url]';
865         }
866
867         /**
868          * Remove image elements and replaces them with links to the image
869          *
870          * @param string $body
871          *
872          * @return string with replaced elements
873          */
874         private static function removePictures($body)
875         {
876                 // Simplify image codes
877                 $body = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '[img]$3[/img]', $body);
878
879                 $body = preg_replace("/\[url=([^\[\]]*)\]\[img\](.*)\[\/img\]\[\/url\]/Usi", '[url]$1[/url]', $body);
880                 $body = preg_replace("/\[img\]([^\[\]]*)\[\/img\]/Usi", '[url]$1[/url]', $body);
881
882                 return $body;
883         }
884
885         /**
886          * Fetches the "context" value for a givem item array from the "conversation" table
887          *
888          * @param array $item
889          *
890          * @return string with context url
891          * @throws \Exception
892          */
893         private static function fetchContextURLForItem($item)
894         {
895                 $conversation = DBA::selectFirst('conversation', ['conversation-href', 'conversation-uri'], ['item-uri' => $item['parent-uri']]);
896                 if (DBA::isResult($conversation) && !empty($conversation['conversation-href'])) {
897                         $context_uri = $conversation['conversation-href'];
898                 } elseif (DBA::isResult($conversation) && !empty($conversation['conversation-uri'])) {
899                         $context_uri = $conversation['conversation-uri'];
900                 } else {
901                         $context_uri = $item['parent-uri'] . '#context';
902                 }
903                 return $context_uri;
904         }
905
906         /**
907          * Returns if the post contains sensitive content ("nsfw")
908          *
909          * @param integer $item_id
910          *
911          * @return boolean
912          * @throws \Exception
913          */
914         private static function isSensitive($item_id)
915         {
916                 $condition = ['otype' => TERM_OBJ_POST, 'oid' => $item_id, 'type' => TERM_HASHTAG, 'term' => 'nsfw'];
917                 return DBA::exists('term', $condition);
918         }
919
920         /**
921          * Creates event data
922          *
923          * @param array $item
924          *
925          * @return array with the event data
926          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
927          */
928         public static function createEvent($item)
929         {
930                 $event = [];
931                 $event['name'] = $item['event-summary'];
932                 $event['content'] = BBCode::convert($item['event-desc'], false, 7);
933                 $event['startTime'] = DateTimeFormat::utc($item['event-start'] . '+00:00', DateTimeFormat::ATOM);
934
935                 if (!$item['event-nofinish']) {
936                         $event['endTime'] = DateTimeFormat::utc($item['event-finish'] . '+00:00', DateTimeFormat::ATOM);
937                 }
938
939                 if (!empty($item['event-location'])) {
940                         $item['location'] = $item['event-location'];
941                         $event['location'] = self::createLocation($item);
942                 }
943
944                 return $event;
945         }
946
947         /**
948          * Creates a note/article object array
949          *
950          * @param array $item
951          *
952          * @return array with the object data
953          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
954          * @throws \ImagickException
955          */
956         public static function createNote($item)
957         {
958                 if ($item['event-type'] == 'event') {
959                         $type = 'Event';
960                 } elseif (!empty($item['title'])) {
961                         $type = 'Article';
962                 } else {
963                         $type = 'Note';
964                 }
965
966                 if ($item['deleted']) {
967                         $type = 'Tombstone';
968                 }
969
970                 $data = [];
971                 $data['id'] = $item['uri'];
972                 $data['type'] = $type;
973
974                 if ($item['deleted']) {
975                         return $data;
976                 }
977
978                 $data['summary'] = null; // Ignore by now
979
980                 if ($item['uri'] != $item['thr-parent']) {
981                         $data['inReplyTo'] = $item['thr-parent'];
982                 } else {
983                         $data['inReplyTo'] = null;
984                 }
985
986                 $data['diaspora:guid'] = $item['guid'];
987                 $data['published'] = DateTimeFormat::utc($item['created'] . '+00:00', DateTimeFormat::ATOM);
988
989                 if ($item['created'] != $item['edited']) {
990                         $data['updated'] = DateTimeFormat::utc($item['edited'] . '+00:00', DateTimeFormat::ATOM);
991                 }
992
993                 $data['url'] = $item['plink'];
994                 $data['attributedTo'] = $item['author-link'];
995                 $data['sensitive'] = self::isSensitive($item['id']);
996                 $data['context'] = self::fetchContextURLForItem($item);
997
998                 if (!empty($item['title'])) {
999                         $data['name'] = BBCode::toPlaintext($item['title'], false);
1000                 }
1001
1002                 $body = $item['body'];
1003
1004                 if ($type == 'Note') {
1005                         $body = self::removePictures($body);
1006                 }
1007
1008                 if ($type == 'Event') {
1009                         $data = array_merge($data, self::createEvent($item));
1010                 } else {
1011                         $regexp = "/[@!]\[url\=([^\[\]]*)\].*?\[\/url\]/ism";
1012                         $body = preg_replace_callback($regexp, ['self', 'mentionCallback'], $body);
1013
1014                         $data['content'] = BBCode::convert($body, false, 7);
1015                 }
1016
1017                 $data['source'] = ['content' => $item['body'], 'mediaType' => "text/bbcode"];
1018
1019                 if (!empty($item['signed_text']) && ($item['uri'] != $item['thr-parent'])) {
1020                         $data['diaspora:comment'] = $item['signed_text'];
1021                 }
1022
1023                 $data['attachment'] = self::createAttachmentList($item, $type);
1024                 $data['tag'] = self::createTagList($item);
1025
1026                 if (empty($data['location']) && (!empty($item['coord']) || !empty($item['location']))) {
1027                         $data['location'] = self::createLocation($item);
1028                 }
1029
1030                 if (!empty($item['app'])) {
1031                         $data['generator'] = ['type' => 'Application', 'name' => $item['app']];
1032                 }
1033
1034                 $data = array_merge($data, self::createPermissionBlockForItem($item, false));
1035
1036                 return $data;
1037         }
1038
1039         /**
1040          * Creates an announce object entry
1041          *
1042          * @param array $item
1043          *
1044          * @return string with announced object url
1045          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1046          * @throws \ImagickException
1047          */
1048         public static function createAnnounce($item)
1049         {
1050                 $announce = api_share_as_retweet($item);
1051                 if (empty($announce['plink'])) {
1052                         return self::createNote($item);
1053                 }
1054
1055                 // Fetch the original id of the object
1056                 $activity = ActivityPub::fetchContent($announce['plink'], $item['uid']);
1057                 if (!empty($activity)) {
1058                         $ldactivity = JsonLD::compact($activity);
1059                         $id = JsonLD::fetchElement($ldactivity, '@id');
1060                         if (!empty($id)) {
1061                                 return $id;
1062                         }
1063                 }
1064
1065                 return self::createNote($item);
1066         }
1067
1068         /**
1069          * Creates an activity id for a given contact id
1070          *
1071          * @param integer $cid Contact ID of target
1072          *
1073          * @return bool|string activity id
1074          */
1075         public static function activityIDFromContact($cid)
1076         {
1077                 $contact = DBA::selectFirst('contact', ['uid', 'id', 'created'], ['id' => $cid]);
1078                 if (!DBA::isResult($contact)) {
1079                         return false;
1080                 }
1081
1082                 $hash = hash('ripemd128', $contact['uid'].'-'.$contact['id'].'-'.$contact['created']);
1083                 $uuid = substr($hash, 0, 8). '-' . substr($hash, 8, 4) . '-' . substr($hash, 12, 4) . '-' . substr($hash, 16, 4) . '-' . substr($hash, 20, 12);
1084                 return System::baseUrl() . '/activity/' . $uuid;
1085         }
1086
1087         /**
1088          * Transmits a contact suggestion to a given inbox
1089          *
1090          * @param integer $uid           User ID
1091          * @param string  $inbox         Target inbox
1092          * @param integer $suggestion_id Suggestion ID
1093          *
1094          * @return boolean was the transmission successful?
1095          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1096          */
1097         public static function sendContactSuggestion($uid, $inbox, $suggestion_id)
1098         {
1099                 $owner = User::getOwnerDataById($uid);
1100
1101                 $suggestion = DBA::selectFirst('fsuggest', ['url', 'note', 'created'], ['id' => $suggestion_id]);
1102
1103                 $data = ['@context' => ActivityPub::CONTEXT,
1104                         'id' => System::baseUrl() . '/activity/' . System::createGUID(),
1105                         'type' => 'Announce',
1106                         'actor' => $owner['url'],
1107                         'object' => $suggestion['url'],
1108                         'content' => $suggestion['note'],
1109                         'instrument' => ['type' => 'Service', 'name' => BaseObject::getApp()->getUserAgent()],
1110                         'to' => [ActivityPub::PUBLIC_COLLECTION],
1111                         'cc' => []];
1112
1113                 $signed = LDSignature::sign($data, $owner);
1114
1115                 Logger::log('Deliver profile deletion for user ' . $uid . ' to ' . $inbox . ' via ActivityPub', Logger::DEBUG);
1116                 return HTTPSignature::transmit($signed, $inbox, $uid);
1117         }
1118
1119         /**
1120          * Transmits a profile relocation to a given inbox
1121          *
1122          * @param integer $uid   User ID
1123          * @param string  $inbox Target inbox
1124          *
1125          * @return boolean was the transmission successful?
1126          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1127          */
1128         public static function sendProfileRelocation($uid, $inbox)
1129         {
1130                 $owner = User::getOwnerDataById($uid);
1131
1132                 $data = ['@context' => ActivityPub::CONTEXT,
1133                         'id' => System::baseUrl() . '/activity/' . System::createGUID(),
1134                         'type' => 'dfrn:relocate',
1135                         'actor' => $owner['url'],
1136                         'object' => $owner['url'],
1137                         'published' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
1138                         'instrument' => ['type' => 'Service', 'name' => BaseObject::getApp()->getUserAgent()],
1139                         'to' => [ActivityPub::PUBLIC_COLLECTION],
1140                         'cc' => []];
1141
1142                 $signed = LDSignature::sign($data, $owner);
1143
1144                 Logger::log('Deliver profile relocation for user ' . $uid . ' to ' . $inbox . ' via ActivityPub', Logger::DEBUG);
1145                 return HTTPSignature::transmit($signed, $inbox, $uid);
1146         }
1147
1148         /**
1149          * Transmits a profile deletion to a given inbox
1150          *
1151          * @param integer $uid   User ID
1152          * @param string  $inbox Target inbox
1153          *
1154          * @return boolean was the transmission successful?
1155          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1156          */
1157         public static function sendProfileDeletion($uid, $inbox)
1158         {
1159                 $owner = User::getOwnerDataById($uid);
1160
1161                 $data = ['@context' => ActivityPub::CONTEXT,
1162                         'id' => System::baseUrl() . '/activity/' . System::createGUID(),
1163                         'type' => 'Delete',
1164                         'actor' => $owner['url'],
1165                         'object' => $owner['url'],
1166                         'published' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
1167                         'instrument' => ['type' => 'Service', 'name' => BaseObject::getApp()->getUserAgent()],
1168                         'to' => [ActivityPub::PUBLIC_COLLECTION],
1169                         'cc' => []];
1170
1171                 $signed = LDSignature::sign($data, $owner);
1172
1173                 Logger::log('Deliver profile deletion for user ' . $uid . ' to ' . $inbox . ' via ActivityPub', Logger::DEBUG);
1174                 return HTTPSignature::transmit($signed, $inbox, $uid);
1175         }
1176
1177         /**
1178          * Transmits a profile change to a given inbox
1179          *
1180          * @param integer $uid   User ID
1181          * @param string  $inbox Target inbox
1182          *
1183          * @return boolean was the transmission successful?
1184          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1185          * @throws \ImagickException
1186          */
1187         public static function sendProfileUpdate($uid, $inbox)
1188         {
1189                 $owner = User::getOwnerDataById($uid);
1190                 $profile = APContact::getByURL($owner['url']);
1191
1192                 $data = ['@context' => ActivityPub::CONTEXT,
1193                         'id' => System::baseUrl() . '/activity/' . System::createGUID(),
1194                         'type' => 'Update',
1195                         'actor' => $owner['url'],
1196                         'object' => self::getProfile($uid),
1197                         'published' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
1198                         'instrument' => ['type' => 'Service', 'name' => BaseObject::getApp()->getUserAgent()],
1199                         'to' => [$profile['followers']],
1200                         'cc' => []];
1201
1202                 $signed = LDSignature::sign($data, $owner);
1203
1204                 Logger::log('Deliver profile update for user ' . $uid . ' to ' . $inbox . ' via ActivityPub', Logger::DEBUG);
1205                 return HTTPSignature::transmit($signed, $inbox, $uid);
1206         }
1207
1208         /**
1209          * Transmits a given activity to a target
1210          *
1211          * @param string  $activity Type name
1212          * @param string  $target   Target profile
1213          * @param integer $uid      User ID
1214          * @return bool
1215          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1216          * @throws \ImagickException
1217          * @throws \Exception
1218          */
1219         public static function sendActivity($activity, $target, $uid, $id = '')
1220         {
1221                 $profile = APContact::getByURL($target);
1222
1223                 $owner = User::getOwnerDataById($uid);
1224
1225                 if (empty($id)) {
1226                         $id = System::baseUrl() . '/activity/' . System::createGUID();
1227                 }
1228
1229                 $data = ['@context' => ActivityPub::CONTEXT,
1230                         'id' => $id,
1231                         'type' => $activity,
1232                         'actor' => $owner['url'],
1233                         'object' => $profile['url'],
1234                         'instrument' => ['type' => 'Service', 'name' => BaseObject::getApp()->getUserAgent()],
1235                         'to' => [$profile['url']]];
1236
1237                 Logger::log('Sending activity ' . $activity . ' to ' . $target . ' for user ' . $uid, Logger::DEBUG);
1238
1239                 $signed = LDSignature::sign($data, $owner);
1240                 return HTTPSignature::transmit($signed, $profile['inbox'], $uid);
1241         }
1242
1243         /**
1244          * Transmit a message that the contact request had been accepted
1245          *
1246          * @param string  $target Target profile
1247          * @param         $id
1248          * @param integer $uid    User ID
1249          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1250          * @throws \ImagickException
1251          */
1252         public static function sendContactAccept($target, $id, $uid)
1253         {
1254                 $profile = APContact::getByURL($target);
1255
1256                 $owner = User::getOwnerDataById($uid);
1257                 $data = ['@context' => ActivityPub::CONTEXT,
1258                         'id' => System::baseUrl() . '/activity/' . System::createGUID(),
1259                         'type' => 'Accept',
1260                         'actor' => $owner['url'],
1261                         'object' => ['id' => $id, 'type' => 'Follow',
1262                                 'actor' => $profile['url'],
1263                                 'object' => $owner['url']],
1264                         'instrument' => ['type' => 'Service', 'name' => BaseObject::getApp()->getUserAgent()],
1265                         'to' => [$profile['url']]];
1266
1267                 Logger::log('Sending accept to ' . $target . ' for user ' . $uid . ' with id ' . $id, Logger::DEBUG);
1268
1269                 $signed = LDSignature::sign($data, $owner);
1270                 HTTPSignature::transmit($signed, $profile['inbox'], $uid);
1271         }
1272
1273         /**
1274          * Reject a contact request or terminates the contact relation
1275          *
1276          * @param string  $target Target profile
1277          * @param         $id
1278          * @param integer $uid    User ID
1279          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1280          * @throws \ImagickException
1281          */
1282         public static function sendContactReject($target, $id, $uid)
1283         {
1284                 $profile = APContact::getByURL($target);
1285
1286                 $owner = User::getOwnerDataById($uid);
1287                 $data = ['@context' => ActivityPub::CONTEXT,
1288                         'id' => System::baseUrl() . '/activity/' . System::createGUID(),
1289                         'type' => 'Reject',
1290                         'actor' => $owner['url'],
1291                         'object' => ['id' => $id, 'type' => 'Follow',
1292                                 'actor' => $profile['url'],
1293                                 'object' => $owner['url']],
1294                         'instrument' => ['type' => 'Service', 'name' => BaseObject::getApp()->getUserAgent()],
1295                         'to' => [$profile['url']]];
1296
1297                 Logger::log('Sending reject to ' . $target . ' for user ' . $uid . ' with id ' . $id, Logger::DEBUG);
1298
1299                 $signed = LDSignature::sign($data, $owner);
1300                 HTTPSignature::transmit($signed, $profile['inbox'], $uid);
1301         }
1302
1303         /**
1304          * Transmits a message that we don't want to follow this contact anymore
1305          *
1306          * @param string  $target Target profile
1307          * @param integer $uid    User ID
1308          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1309          * @throws \ImagickException
1310          * @throws \Exception
1311          */
1312         public static function sendContactUndo($target, $cid, $uid)
1313         {
1314                 $profile = APContact::getByURL($target);
1315
1316                 $object_id = self::activityIDFromContact($cid);
1317                 if (empty($object_id)) {
1318                         return;
1319                 }
1320
1321                 $id = System::baseUrl() . '/activity/' . System::createGUID();
1322
1323                 $owner = User::getOwnerDataById($uid);
1324                 $data = ['@context' => ActivityPub::CONTEXT,
1325                         'id' => $id,
1326                         'type' => 'Undo',
1327                         'actor' => $owner['url'],
1328                         'object' => ['id' => $object_id, 'type' => 'Follow',
1329                                 'actor' => $owner['url'],
1330                                 'object' => $profile['url']],
1331                         'instrument' => ['type' => 'Service', 'name' => BaseObject::getApp()->getUserAgent()],
1332                         'to' => [$profile['url']]];
1333
1334                 Logger::log('Sending undo to ' . $target . ' for user ' . $uid . ' with id ' . $id, Logger::DEBUG);
1335
1336                 $signed = LDSignature::sign($data, $owner);
1337                 HTTPSignature::transmit($signed, $profile['inbox'], $uid);
1338         }
1339 }