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