Merge pull request #6566 from annando/ap-debug
[friendica.git/.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                 if (Config::get('debug', 'total_ap_delivery')) {
329                         // Will be activated in a later step
330                         $networks = [Protocol::ACTIVITYPUB, Protocol::DFRN, Protocol::DIASPORA, Protocol::OSTATUS];
331                 } else {
332                         // For now only send to these contacts:
333                         $networks = [Protocol::ACTIVITYPUB, Protocol::OSTATUS];
334                 }
335
336                 $data = ['to' => [], 'cc' => [], 'bcc' => []];
337
338                 if ($item['gravity'] == GRAVITY_PARENT) {
339                         $actor_profile = APContact::getByURL($item['owner-link']);
340                 } else {
341                         $actor_profile = APContact::getByURL($item['author-link']);
342                 }
343
344                 $terms = Term::tagArrayFromItemId($item['id'], TERM_MENTION);
345
346                 if (!$item['private']) {
347                         $data = array_merge($data, self::fetchPermissionBlockFromConversation($item));
348
349                         $data['to'][] = ActivityPub::PUBLIC_COLLECTION;
350
351                         foreach ($terms as $term) {
352                                 $profile = APContact::getByURL($term['url'], false);
353                                 if (!empty($profile)) {
354                                         $data['to'][] = $profile['url'];
355                                 }
356                         }
357                 } else {
358                         $receiver_list = Item::enumeratePermissions($item);
359
360                         foreach ($terms as $term) {
361                                 $cid = Contact::getIdForURL($term['url'], $item['uid']);
362                                 if (!empty($cid) && in_array($cid, $receiver_list)) {
363                                         $contact = DBA::selectFirst('contact', ['url'], ['id' => $cid, 'network' => $networks]);
364                                         if (DBA::isResult($contact) && !empty($profile = APContact::getByURL($contact['url'], false))) {
365                                                 $data['to'][] = $profile['url'];
366                                         }
367                                 }
368                         }
369
370                         foreach ($receiver_list as $receiver) {
371                                 $contact = DBA::selectFirst('contact', ['url', 'hidden'], ['id' => $receiver, 'network' => $networks]);
372                                 if (DBA::isResult($contact) && !empty($profile = APContact::getByURL($contact['url'], false))) {
373                                         if ($contact['hidden'] || $always_bcc) {
374                                                 $data['bcc'][] = $profile['url'];
375                                         } else {
376                                                 $data['cc'][] = $profile['url'];
377                                         }
378                                 }
379                         }
380                 }
381
382                 $parents = Item::select(['id', 'author-link', 'owner-link', 'gravity', 'uri'], ['parent' => $item['parent']]);
383                 while ($parent = Item::fetch($parents)) {
384                         if ($parent['gravity'] == GRAVITY_PARENT) {
385                                 $profile = APContact::getByURL($parent['owner-link'], false);
386                                 if (!empty($profile)) {
387                                         if ($item['gravity'] != GRAVITY_PARENT) {
388                                                 // Comments to forums are directed to the forum
389                                                 // But comments to forums aren't directed to the followers collection
390                                                 if ($profile['type'] == 'Group') {
391                                                         $data['to'][] = $profile['url'];
392                                                 } else {
393                                                         $data['cc'][] = $profile['url'];
394                                                         if (!$item['private']) {
395                                                                 $data['cc'][] = $actor_profile['followers'];
396                                                         }
397                                                 }
398                                         } else {
399                                                 // Public thread parent post always are directed to the followes
400                                                 if (!$item['private']) {
401                                                         $data['cc'][] = $actor_profile['followers'];
402                                                 }
403                                         }
404                                 }
405                         }
406
407                         // Don't include data from future posts
408                         if ($parent['id'] >= $last_id) {
409                                 continue;
410                         }
411
412                         $profile = APContact::getByURL($parent['author-link'], false);
413                         if (!empty($profile)) {
414                                 if (($profile['type'] == 'Group') || ($parent['uri'] == $item['thr-parent'])) {
415                                         $data['to'][] = $profile['url'];
416                                 } else {
417                                         $data['cc'][] = $profile['url'];
418                                 }
419                         }
420                 }
421                 DBA::close($parents);
422
423                 $data['to'] = array_unique($data['to']);
424                 $data['cc'] = array_unique($data['cc']);
425                 $data['bcc'] = array_unique($data['bcc']);
426
427                 if (($key = array_search($item['author-link'], $data['to'])) !== false) {
428                         unset($data['to'][$key]);
429                 }
430
431                 if (($key = array_search($item['author-link'], $data['cc'])) !== false) {
432                         unset($data['cc'][$key]);
433                 }
434
435                 if (($key = array_search($item['author-link'], $data['bcc'])) !== false) {
436                         unset($data['bcc'][$key]);
437                 }
438
439                 foreach ($data['to'] as $to) {
440                         if (($key = array_search($to, $data['cc'])) !== false) {
441                                 unset($data['cc'][$key]);
442                         }
443
444                         if (($key = array_search($to, $data['bcc'])) !== false) {
445                                 unset($data['bcc'][$key]);
446                         }
447                 }
448
449                 foreach ($data['cc'] as $cc) {
450                         if (($key = array_search($cc, $data['bcc'])) !== false) {
451                                 unset($data['bcc'][$key]);
452                         }
453                 }
454
455                 $receivers = ['to' => array_values($data['to']), 'cc' => array_values($data['cc']), 'bcc' => array_values($data['bcc'])];
456
457                 if (!$blindcopy) {
458                         unset($receivers['bcc']);
459                 }
460
461                 return $receivers;
462         }
463
464         /**
465          * Fetches a list of inboxes of followers of a given user
466          *
467          * @param integer $uid      User ID
468          * @param boolean $personal fetch personal inboxes
469          *
470          * @return array of follower inboxes
471          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
472          * @throws \ImagickException
473          */
474         public static function fetchTargetInboxesforUser($uid, $personal = false)
475         {
476                 $inboxes = [];
477
478                 if (Config::get('debug', 'total_ap_delivery')) {
479                         // Will be activated in a later step
480                         $networks = [Protocol::ACTIVITYPUB, Protocol::DFRN, Protocol::DIASPORA, Protocol::OSTATUS];
481                 } else {
482                         // For now only send to these contacts:
483                         $networks = [Protocol::ACTIVITYPUB, Protocol::OSTATUS];
484                 }
485
486                 $condition = ['uid' => $uid, 'network' => $networks, 'archive' => false, 'pending' => false];
487
488                 if (!empty($uid)) {
489                         $condition['rel'] = [Contact::FOLLOWER, Contact::FRIEND];
490                 }
491
492                 $contacts = DBA::select('contact', ['url'], $condition);
493                 while ($contact = DBA::fetch($contacts)) {
494                         if (Network::isUrlBlocked($contact['url'])) {
495                                 continue;
496                         }
497
498                         $profile = APContact::getByURL($contact['url'], false);
499                         if (!empty($profile)) {
500                                 if (empty($profile['sharedinbox']) || $personal) {
501                                         $target = $profile['inbox'];
502                                 } else {
503                                         $target = $profile['sharedinbox'];
504                                 }
505                                 $inboxes[$target] = $target;
506                         }
507                 }
508                 DBA::close($contacts);
509
510                 return $inboxes;
511         }
512
513         /**
514          * Fetches an array of inboxes for the given item and user
515          *
516          * @param array   $item
517          * @param integer $uid      User ID
518          * @param boolean $personal fetch personal inboxes
519          * @param integer $last_id Last item id for adding receivers
520          *
521          * @return array with inboxes
522          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
523          * @throws \ImagickException
524          */
525         public static function fetchTargetInboxes($item, $uid, $personal = false, $last_id = 0)
526         {
527                 $permissions = self::createPermissionBlockForItem($item, true, $last_id);
528                 if (empty($permissions)) {
529                         return [];
530                 }
531
532                 $inboxes = [];
533
534                 if ($item['gravity'] == GRAVITY_ACTIVITY) {
535                         $item_profile = APContact::getByURL($item['author-link'], false);
536                 } else {
537                         $item_profile = APContact::getByURL($item['owner-link'], false);
538                 }
539
540                 foreach (['to', 'cc', 'bto', 'bcc'] as $element) {
541                         if (empty($permissions[$element])) {
542                                 continue;
543                         }
544
545                         $blindcopy = in_array($element, ['bto', 'bcc']);
546
547                         foreach ($permissions[$element] as $receiver) {
548                                 if (Network::isUrlBlocked($receiver)) {
549                                         continue;
550                                 }
551
552                                 if ($receiver == $item_profile['followers']) {
553                                         $inboxes = array_merge($inboxes, self::fetchTargetInboxesforUser($uid, $personal));
554                                 } else {
555                                         $profile = APContact::getByURL($receiver, false);
556                                         if (!empty($profile)) {
557                                                 if (empty($profile['sharedinbox']) || $personal || $blindcopy) {
558                                                         $target = $profile['inbox'];
559                                                 } else {
560                                                         $target = $profile['sharedinbox'];
561                                                 }
562                                                 $inboxes[$target] = $target;
563                                         }
564                                 }
565                         }
566                 }
567
568                 return $inboxes;
569         }
570
571         /**
572          * Returns the activity type of a given item
573          *
574          * @param array $item
575          *
576          * @return string with activity type
577          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
578          * @throws \ImagickException
579          */
580         private static function getTypeOfItem($item)
581         {
582                 $reshared = false;
583
584                 // Only check for a reshare, if it is a real reshare and no quoted reshare
585                 if (strpos($item['body'], "[share") === 0) {
586                         $announce = api_share_as_retweet($item);
587                         $reshared = !empty($announce['plink']);
588                 }
589
590                 if ($reshared) {
591                         $type = 'Announce';
592                 } elseif ($item['verb'] == ACTIVITY_POST) {
593                         if ($item['created'] == $item['edited']) {
594                                 $type = 'Create';
595                         } else {
596                                 $type = 'Update';
597                         }
598                 } elseif ($item['verb'] == ACTIVITY_LIKE) {
599                         $type = 'Like';
600                 } elseif ($item['verb'] == ACTIVITY_DISLIKE) {
601                         $type = 'Dislike';
602                 } elseif ($item['verb'] == ACTIVITY_ATTEND) {
603                         $type = 'Accept';
604                 } elseif ($item['verb'] == ACTIVITY_ATTENDNO) {
605                         $type = 'Reject';
606                 } elseif ($item['verb'] == ACTIVITY_ATTENDMAYBE) {
607                         $type = 'TentativeAccept';
608                 } elseif ($item['verb'] == ACTIVITY_FOLLOW) {
609                         $type = 'Follow';
610                 } else {
611                         $type = '';
612                 }
613
614                 return $type;
615         }
616
617         /**
618          * Creates the activity or fetches it from the cache
619          *
620          * @param integer $item_id
621          * @param boolean $force Force new cache entry
622          *
623          * @return array with the activity
624          * @throws \Exception
625          */
626         public static function createCachedActivityFromItem($item_id, $force = false)
627         {
628                 $cachekey = 'APDelivery:createActivity:' . $item_id;
629
630                 if (!$force) {
631                         $data = Cache::get($cachekey);
632                         if (!is_null($data)) {
633                                 return $data;
634                         }
635                 }
636
637                 $data = ActivityPub\Transmitter::createActivityFromItem($item_id);
638
639                 Cache::set($cachekey, $data, Cache::QUARTER_HOUR);
640                 return $data;
641         }
642
643         /**
644          * Creates an activity array for a given item id
645          *
646          * @param integer $item_id
647          * @param boolean $object_mode Is the activity item is used inside another object?
648          *
649          * @return array of activity
650          * @throws \Exception
651          */
652         public static function createActivityFromItem($item_id, $object_mode = false)
653         {
654                 $item = Item::selectFirst([], ['id' => $item_id, 'parent-network' => Protocol::NATIVE_SUPPORT]);
655
656                 if (!DBA::isResult($item)) {
657                         return false;
658                 }
659
660                 if ($item['wall']) {
661                         $owner = User::getOwnerDataById($item['uid']);
662                         if (($owner['account-type'] == User::ACCOUNT_TYPE_COMMUNITY) && ($item['author-link'] != $owner['url'])) {
663                                 $type = 'Announce';
664
665                                 // Disguise forum posts as reshares. Will later be converted to a real announce
666                                 $item['body'] = share_header($item['author-name'], $item['author-link'], $item['author-avatar'],
667                                         $item['guid'], $item['created'], $item['plink']) . $item['body'] . '[/share]';
668                         }
669                 }
670
671                 if (empty($type)) {
672                         $condition = ['item-uri' => $item['uri'], 'protocol' => Conversation::PARCEL_ACTIVITYPUB];
673                         $conversation = DBA::selectFirst('conversation', ['source'], $condition);
674                         if (DBA::isResult($conversation)) {
675                                 $data = json_decode($conversation['source']);
676                                 if (!empty($data)) {
677                                         return $data;
678                                 }
679                         }
680
681                         $type = self::getTypeOfItem($item);
682                 }
683
684                 if (!$object_mode) {
685                         $data = ['@context' => ActivityPub::CONTEXT];
686
687                         if ($item['deleted'] && ($item['gravity'] == GRAVITY_ACTIVITY)) {
688                                 $type = 'Undo';
689                         } elseif ($item['deleted']) {
690                                 $type = 'Delete';
691                         }
692                 } else {
693                         $data = [];
694                 }
695
696                 $data['id'] = $item['uri'] . '#' . $type;
697                 $data['type'] = $type;
698                 $data['actor'] = $item['owner-link'];
699
700                 $data['published'] = DateTimeFormat::utc($item['created'] . '+00:00', DateTimeFormat::ATOM);
701
702                 $data['instrument'] = ['type' => 'Service', 'name' => BaseObject::getApp()->getUserAgent()];
703
704                 $data = array_merge($data, self::createPermissionBlockForItem($item, false));
705
706                 if (in_array($data['type'], ['Create', 'Update', 'Delete'])) {
707                         $data['object'] = self::createNote($item);
708                 } elseif ($data['type'] == 'Announce') {
709                         $data = self::createAnnounce($item, $data);
710                 } elseif ($data['type'] == 'Follow') {
711                         $data['object'] = $item['parent-uri'];
712                 } elseif ($data['type'] == 'Undo') {
713                         $data['object'] = self::createActivityFromItem($item_id, true);
714                 } else {
715                         $data['diaspora:guid'] = $item['guid'];
716                         if (!empty($item['signed_text'])) {
717                                 $data['diaspora:like'] = $item['signed_text'];
718                         }
719                         $data['object'] = $item['thr-parent'];
720                 }
721
722                 if (!empty($item['contact-uid'])) {
723                         $uid = $item['contact-uid'];
724                 } else {
725                         $uid = $item['uid'];
726                 }
727
728                 $owner = User::getOwnerDataById($uid);
729
730                 if (!$object_mode && !empty($owner)) {
731                         return LDSignature::sign($data, $owner);
732                 } else {
733                         return $data;
734                 }
735
736                 /// @todo Create "conversation" entry
737         }
738
739         /**
740          * Creates an object array for a given item id
741          *
742          * @param integer $item_id
743          *
744          * @return array with the object data
745          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
746          * @throws \ImagickException
747          */
748         public static function createObjectFromItemID($item_id)
749         {
750                 $item = Item::selectFirst([], ['id' => $item_id, 'parent-network' => Protocol::NATIVE_SUPPORT]);
751
752                 if (!DBA::isResult($item)) {
753                         return false;
754                 }
755
756                 $data = ['@context' => ActivityPub::CONTEXT];
757                 $data = array_merge($data, self::createNote($item));
758
759                 return $data;
760         }
761
762         /**
763          * Creates a location entry for a given item array
764          *
765          * @param array $item
766          *
767          * @return array with location array
768          */
769         private static function createLocation($item)
770         {
771                 $location = ['type' => 'Place'];
772
773                 if (!empty($item['location'])) {
774                         $location['name'] = $item['location'];
775                 }
776
777                 $coord = [];
778
779                 if (empty($item['coord'])) {
780                         $coord = Map::getCoordinates($item['location']);
781                 } else {
782                         $coords = explode(' ', $item['coord']);
783                         if (count($coords) == 2) {
784                                 $coord = ['lat' => $coords[0], 'lon' => $coords[1]];
785                         }
786                 }
787
788                 if (!empty($coord['lat']) && !empty($coord['lon'])) {
789                         $location['latitude'] = $coord['lat'];
790                         $location['longitude'] = $coord['lon'];
791                 }
792
793                 return $location;
794         }
795
796         /**
797          * Returns a tag array for a given item array
798          *
799          * @param array $item
800          *
801          * @return array of tags
802          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
803          */
804         private static function createTagList($item)
805         {
806                 $tags = [];
807
808                 $terms = Term::tagArrayFromItemId($item['id']);
809                 foreach ($terms as $term) {
810                         if ($term['type'] == TERM_HASHTAG) {
811                                 $url = System::baseUrl() . '/search?tag=' . urlencode($term['term']);
812                                 $tags[] = ['type' => 'Hashtag', 'href' => $url, 'name' => '#' . $term['term']];
813                         } elseif ($term['type'] == TERM_MENTION) {
814                                 $contact = Contact::getDetailsByURL($term['url']);
815                                 if (!empty($contact['addr'])) {
816                                         $mention = '@' . $contact['addr'];
817                                 } else {
818                                         $mention = '@' . $term['url'];
819                                 }
820
821                                 $tags[] = ['type' => 'Mention', 'href' => $term['url'], 'name' => $mention];
822                         }
823                 }
824                 return $tags;
825         }
826
827         /**
828          * Adds attachment data to the JSON document
829          *
830          * @param array  $item Data of the item that is to be posted
831          * @param string $type Object type
832          *
833          * @return array with attachment data
834          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
835          */
836         private static function createAttachmentList($item, $type)
837         {
838                 $attachments = [];
839
840                 $arr = explode('[/attach],', $item['attach']);
841                 if (count($arr)) {
842                         foreach ($arr as $r) {
843                                 $matches = false;
844                                 $cnt = preg_match('|\[attach\]href=\"(.*?)\" length=\"(.*?)\" type=\"(.*?)\" title=\"(.*?)\"|', $r, $matches);
845                                 if ($cnt) {
846                                         $attributes = ['type' => 'Document',
847                                                         'mediaType' => $matches[3],
848                                                         'url' => $matches[1],
849                                                         'name' => null];
850
851                                         if (trim($matches[4]) != '') {
852                                                 $attributes['name'] = trim($matches[4]);
853                                         }
854
855                                         $attachments[] = $attributes;
856                                 }
857                         }
858                 }
859
860                 if ($type != 'Note') {
861                         return $attachments;
862                 }
863
864                 // Simplify image codes
865                 $body = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '[img]$3[/img]', $item['body']);
866
867                 // Grab all pictures and create attachments out of them
868                 if (preg_match_all("/\[img\]([^\[\]]*)\[\/img\]/Usi", $body, $pictures)) {
869                         foreach ($pictures[1] as $picture) {
870                                 $imgdata = Image::getInfoFromURL($picture);
871                                 if ($imgdata) {
872                                         $attachments[] = ['type' => 'Document',
873                                                 'mediaType' => $imgdata['mime'],
874                                                 'url' => $picture,
875                                                 'name' => null];
876                                 }
877                         }
878                 }
879
880                 return $attachments;
881         }
882
883         /**
884          * @brief Callback function to replace a Friendica style mention in a mention that is used on AP
885          *
886          * @param array $match Matching values for the callback
887          * @return string Replaced mention
888          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
889          */
890         private static function mentionCallback($match)
891         {
892                 if (empty($match[1])) {
893                         return;
894                 }
895
896                 $data = Contact::getDetailsByURL($match[1]);
897                 if (empty($data) || empty($data['nick'])) {
898                         return;
899                 }
900
901                 return '@[url=' . $data['url'] . ']' . $data['nick'] . '[/url]';
902         }
903
904         /**
905          * Remove image elements and replaces them with links to the image
906          *
907          * @param string $body
908          *
909          * @return string with replaced elements
910          */
911         private static function removePictures($body)
912         {
913                 // Simplify image codes
914                 $body = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '[img]$3[/img]', $body);
915
916                 $body = preg_replace("/\[url=([^\[\]]*)\]\[img\](.*)\[\/img\]\[\/url\]/Usi", '[url]$1[/url]', $body);
917                 $body = preg_replace("/\[img\]([^\[\]]*)\[\/img\]/Usi", '[url]$1[/url]', $body);
918
919                 return $body;
920         }
921
922         /**
923          * Fetches the "context" value for a givem item array from the "conversation" table
924          *
925          * @param array $item
926          *
927          * @return string with context url
928          * @throws \Exception
929          */
930         private static function fetchContextURLForItem($item)
931         {
932                 $conversation = DBA::selectFirst('conversation', ['conversation-href', 'conversation-uri'], ['item-uri' => $item['parent-uri']]);
933                 if (DBA::isResult($conversation) && !empty($conversation['conversation-href'])) {
934                         $context_uri = $conversation['conversation-href'];
935                 } elseif (DBA::isResult($conversation) && !empty($conversation['conversation-uri'])) {
936                         $context_uri = $conversation['conversation-uri'];
937                 } else {
938                         $context_uri = $item['parent-uri'] . '#context';
939                 }
940                 return $context_uri;
941         }
942
943         /**
944          * Returns if the post contains sensitive content ("nsfw")
945          *
946          * @param integer $item_id
947          *
948          * @return boolean
949          * @throws \Exception
950          */
951         private static function isSensitive($item_id)
952         {
953                 $condition = ['otype' => TERM_OBJ_POST, 'oid' => $item_id, 'type' => TERM_HASHTAG, 'term' => 'nsfw'];
954                 return DBA::exists('term', $condition);
955         }
956
957         /**
958          * Creates event data
959          *
960          * @param array $item
961          *
962          * @return array with the event data
963          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
964          */
965         public static function createEvent($item)
966         {
967                 $event = [];
968                 $event['name'] = $item['event-summary'];
969                 $event['content'] = BBCode::convert($item['event-desc'], false, 7);
970                 $event['startTime'] = DateTimeFormat::utc($item['event-start'] . '+00:00', DateTimeFormat::ATOM);
971
972                 if (!$item['event-nofinish']) {
973                         $event['endTime'] = DateTimeFormat::utc($item['event-finish'] . '+00:00', DateTimeFormat::ATOM);
974                 }
975
976                 if (!empty($item['event-location'])) {
977                         $item['location'] = $item['event-location'];
978                         $event['location'] = self::createLocation($item);
979                 }
980
981                 return $event;
982         }
983
984         /**
985          * Creates a note/article object array
986          *
987          * @param array $item
988          *
989          * @return array with the object data
990          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
991          * @throws \ImagickException
992          */
993         public static function createNote($item)
994         {
995                 if ($item['event-type'] == 'event') {
996                         $type = 'Event';
997                 } elseif (!empty($item['title'])) {
998                         $type = 'Article';
999                 } else {
1000                         $type = 'Note';
1001                 }
1002
1003                 if ($item['deleted']) {
1004                         $type = 'Tombstone';
1005                 }
1006
1007                 $data = [];
1008                 $data['id'] = $item['uri'];
1009                 $data['type'] = $type;
1010
1011                 if ($item['deleted']) {
1012                         return $data;
1013                 }
1014
1015                 $data['summary'] = null; // Ignore by now
1016
1017                 if ($item['uri'] != $item['thr-parent']) {
1018                         $data['inReplyTo'] = $item['thr-parent'];
1019                 } else {
1020                         $data['inReplyTo'] = null;
1021                 }
1022
1023                 $data['diaspora:guid'] = $item['guid'];
1024                 $data['published'] = DateTimeFormat::utc($item['created'] . '+00:00', DateTimeFormat::ATOM);
1025
1026                 if ($item['created'] != $item['edited']) {
1027                         $data['updated'] = DateTimeFormat::utc($item['edited'] . '+00:00', DateTimeFormat::ATOM);
1028                 }
1029
1030                 $data['url'] = $item['plink'];
1031                 $data['attributedTo'] = $item['author-link'];
1032                 $data['sensitive'] = self::isSensitive($item['id']);
1033                 $data['context'] = self::fetchContextURLForItem($item);
1034
1035                 if (!empty($item['title'])) {
1036                         $data['name'] = BBCode::toPlaintext($item['title'], false);
1037                 }
1038
1039                 $body = $item['body'];
1040
1041                 if ($type == 'Note') {
1042                         $body = self::removePictures($body);
1043                 }
1044
1045                 if ($type == 'Event') {
1046                         $data = array_merge($data, self::createEvent($item));
1047                 } else {
1048                         $regexp = "/[@!]\[url\=([^\[\]]*)\].*?\[\/url\]/ism";
1049                         $body = preg_replace_callback($regexp, ['self', 'mentionCallback'], $body);
1050
1051                         $data['content'] = BBCode::convert($body, false, 7);
1052                 }
1053
1054                 $data['source'] = ['content' => $item['body'], 'mediaType' => "text/bbcode"];
1055
1056                 if (!empty($item['signed_text']) && ($item['uri'] != $item['thr-parent'])) {
1057                         $data['diaspora:comment'] = $item['signed_text'];
1058                 }
1059
1060                 $data['attachment'] = self::createAttachmentList($item, $type);
1061                 $data['tag'] = self::createTagList($item);
1062
1063                 if (empty($data['location']) && (!empty($item['coord']) || !empty($item['location']))) {
1064                         $data['location'] = self::createLocation($item);
1065                 }
1066
1067                 if (!empty($item['app'])) {
1068                         $data['generator'] = ['type' => 'Application', 'name' => $item['app']];
1069                 }
1070
1071                 $data = array_merge($data, self::createPermissionBlockForItem($item, false));
1072
1073                 return $data;
1074         }
1075
1076         /**
1077          * Creates an announce object entry
1078          *
1079          * @param array $item
1080          * @param array $data activity data
1081          *
1082          * @return array with activity data
1083          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1084          * @throws \ImagickException
1085          */
1086         private static function createAnnounce($item, $data)
1087         {
1088                 $announce = api_share_as_retweet($item);
1089                 if (empty($announce['plink'])) {
1090                         $data['type'] = 'Create';
1091                         $data['object'] = self::createNote($item);
1092                         return $data;
1093                 }
1094
1095                 // Fetch the original id of the object
1096                 $activity = ActivityPub::fetchContent($announce['plink'], $item['uid']);
1097                 if (!empty($activity)) {
1098                         $ldactivity = JsonLD::compact($activity);
1099                         $id = JsonLD::fetchElement($ldactivity, '@id');
1100                         if (!empty($id)) {
1101                                 $data['object'] = $id;
1102                                 return $data;
1103                         }
1104                 }
1105
1106                 $data['type'] = 'Create';
1107                 $data['object'] = self::createNote($item);
1108                 return $data;
1109         }
1110
1111         /**
1112          * Creates an activity id for a given contact id
1113          *
1114          * @param integer $cid Contact ID of target
1115          *
1116          * @return bool|string activity id
1117          */
1118         public static function activityIDFromContact($cid)
1119         {
1120                 $contact = DBA::selectFirst('contact', ['uid', 'id', 'created'], ['id' => $cid]);
1121                 if (!DBA::isResult($contact)) {
1122                         return false;
1123                 }
1124
1125                 $hash = hash('ripemd128', $contact['uid'].'-'.$contact['id'].'-'.$contact['created']);
1126                 $uuid = substr($hash, 0, 8). '-' . substr($hash, 8, 4) . '-' . substr($hash, 12, 4) . '-' . substr($hash, 16, 4) . '-' . substr($hash, 20, 12);
1127                 return System::baseUrl() . '/activity/' . $uuid;
1128         }
1129
1130         /**
1131          * Transmits a contact suggestion to a given inbox
1132          *
1133          * @param integer $uid           User ID
1134          * @param string  $inbox         Target inbox
1135          * @param integer $suggestion_id Suggestion ID
1136          *
1137          * @return boolean was the transmission successful?
1138          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1139          */
1140         public static function sendContactSuggestion($uid, $inbox, $suggestion_id)
1141         {
1142                 $owner = User::getOwnerDataById($uid);
1143
1144                 $suggestion = DBA::selectFirst('fsuggest', ['url', 'note', 'created'], ['id' => $suggestion_id]);
1145
1146                 $data = ['@context' => ActivityPub::CONTEXT,
1147                         'id' => System::baseUrl() . '/activity/' . System::createGUID(),
1148                         'type' => 'Announce',
1149                         'actor' => $owner['url'],
1150                         'object' => $suggestion['url'],
1151                         'content' => $suggestion['note'],
1152                         'instrument' => ['type' => 'Service', 'name' => BaseObject::getApp()->getUserAgent()],
1153                         'to' => [ActivityPub::PUBLIC_COLLECTION],
1154                         'cc' => []];
1155
1156                 $signed = LDSignature::sign($data, $owner);
1157
1158                 Logger::log('Deliver profile deletion for user ' . $uid . ' to ' . $inbox . ' via ActivityPub', Logger::DEBUG);
1159                 return HTTPSignature::transmit($signed, $inbox, $uid);
1160         }
1161
1162         /**
1163          * Transmits a profile relocation to a given inbox
1164          *
1165          * @param integer $uid   User ID
1166          * @param string  $inbox Target inbox
1167          *
1168          * @return boolean was the transmission successful?
1169          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1170          */
1171         public static function sendProfileRelocation($uid, $inbox)
1172         {
1173                 $owner = User::getOwnerDataById($uid);
1174
1175                 $data = ['@context' => ActivityPub::CONTEXT,
1176                         'id' => System::baseUrl() . '/activity/' . System::createGUID(),
1177                         'type' => 'dfrn:relocate',
1178                         'actor' => $owner['url'],
1179                         'object' => $owner['url'],
1180                         'published' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
1181                         'instrument' => ['type' => 'Service', 'name' => BaseObject::getApp()->getUserAgent()],
1182                         'to' => [ActivityPub::PUBLIC_COLLECTION],
1183                         'cc' => []];
1184
1185                 $signed = LDSignature::sign($data, $owner);
1186
1187                 Logger::log('Deliver profile relocation for user ' . $uid . ' to ' . $inbox . ' via ActivityPub', Logger::DEBUG);
1188                 return HTTPSignature::transmit($signed, $inbox, $uid);
1189         }
1190
1191         /**
1192          * Transmits a profile deletion to a given inbox
1193          *
1194          * @param integer $uid   User ID
1195          * @param string  $inbox Target inbox
1196          *
1197          * @return boolean was the transmission successful?
1198          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1199          */
1200         public static function sendProfileDeletion($uid, $inbox)
1201         {
1202                 $owner = User::getOwnerDataById($uid);
1203
1204                 $data = ['@context' => ActivityPub::CONTEXT,
1205                         'id' => System::baseUrl() . '/activity/' . System::createGUID(),
1206                         'type' => 'Delete',
1207                         'actor' => $owner['url'],
1208                         'object' => $owner['url'],
1209                         'published' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
1210                         'instrument' => ['type' => 'Service', 'name' => BaseObject::getApp()->getUserAgent()],
1211                         'to' => [ActivityPub::PUBLIC_COLLECTION],
1212                         'cc' => []];
1213
1214                 $signed = LDSignature::sign($data, $owner);
1215
1216                 Logger::log('Deliver profile deletion for user ' . $uid . ' to ' . $inbox . ' via ActivityPub', Logger::DEBUG);
1217                 return HTTPSignature::transmit($signed, $inbox, $uid);
1218         }
1219
1220         /**
1221          * Transmits a profile change to a given inbox
1222          *
1223          * @param integer $uid   User ID
1224          * @param string  $inbox Target inbox
1225          *
1226          * @return boolean was the transmission successful?
1227          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1228          * @throws \ImagickException
1229          */
1230         public static function sendProfileUpdate($uid, $inbox)
1231         {
1232                 $owner = User::getOwnerDataById($uid);
1233                 $profile = APContact::getByURL($owner['url']);
1234
1235                 $data = ['@context' => ActivityPub::CONTEXT,
1236                         'id' => System::baseUrl() . '/activity/' . System::createGUID(),
1237                         'type' => 'Update',
1238                         'actor' => $owner['url'],
1239                         'object' => self::getProfile($uid),
1240                         'published' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
1241                         'instrument' => ['type' => 'Service', 'name' => BaseObject::getApp()->getUserAgent()],
1242                         'to' => [$profile['followers']],
1243                         'cc' => []];
1244
1245                 $signed = LDSignature::sign($data, $owner);
1246
1247                 Logger::log('Deliver profile update for user ' . $uid . ' to ' . $inbox . ' via ActivityPub', Logger::DEBUG);
1248                 return HTTPSignature::transmit($signed, $inbox, $uid);
1249         }
1250
1251         /**
1252          * Transmits a given activity to a target
1253          *
1254          * @param string  $activity Type name
1255          * @param string  $target   Target profile
1256          * @param integer $uid      User ID
1257          * @return bool
1258          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1259          * @throws \ImagickException
1260          * @throws \Exception
1261          */
1262         public static function sendActivity($activity, $target, $uid, $id = '')
1263         {
1264                 $profile = APContact::getByURL($target);
1265
1266                 $owner = User::getOwnerDataById($uid);
1267
1268                 if (empty($id)) {
1269                         $id = System::baseUrl() . '/activity/' . System::createGUID();
1270                 }
1271
1272                 $data = ['@context' => ActivityPub::CONTEXT,
1273                         'id' => $id,
1274                         'type' => $activity,
1275                         'actor' => $owner['url'],
1276                         'object' => $profile['url'],
1277                         'instrument' => ['type' => 'Service', 'name' => BaseObject::getApp()->getUserAgent()],
1278                         'to' => [$profile['url']]];
1279
1280                 Logger::log('Sending activity ' . $activity . ' to ' . $target . ' for user ' . $uid, Logger::DEBUG);
1281
1282                 $signed = LDSignature::sign($data, $owner);
1283                 return HTTPSignature::transmit($signed, $profile['inbox'], $uid);
1284         }
1285
1286         /**
1287          * Transmits a "follow object" activity to a target
1288          * This is a preparation for sending automated "follow" requests when receiving "Announce" messages
1289          *
1290          * @param string  $object Object URL
1291          * @param string  $target Target profile
1292          * @param integer $uid    User ID
1293          * @return bool
1294          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1295          * @throws \ImagickException
1296          * @throws \Exception
1297          */
1298         public static function sendFollowObject($object, $target, $uid)
1299         {
1300                 $profile = APContact::getByURL($target);
1301
1302                 $owner = User::getOwnerDataById($uid);
1303
1304                 $data = ['@context' => ActivityPub::CONTEXT,
1305                         'id' => System::baseUrl() . '/activity/' . System::createGUID(),
1306                         'type' => 'Follow',
1307                         'actor' => $owner['url'],
1308                         'object' => $object,
1309                         'instrument' => ['type' => 'Service', 'name' => BaseObject::getApp()->getUserAgent()],
1310                         'to' => [$profile['url']]];
1311
1312                 Logger::log('Sending follow ' . $object . ' to ' . $target . ' for user ' . $uid, Logger::DEBUG);
1313
1314                 $signed = LDSignature::sign($data, $owner);
1315                 return HTTPSignature::transmit($signed, $profile['inbox'], $uid);
1316         }
1317
1318         /**
1319          * Transmit a message that the contact request had been accepted
1320          *
1321          * @param string  $target Target profile
1322          * @param         $id
1323          * @param integer $uid    User ID
1324          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1325          * @throws \ImagickException
1326          */
1327         public static function sendContactAccept($target, $id, $uid)
1328         {
1329                 $profile = APContact::getByURL($target);
1330
1331                 $owner = User::getOwnerDataById($uid);
1332                 $data = ['@context' => ActivityPub::CONTEXT,
1333                         'id' => System::baseUrl() . '/activity/' . System::createGUID(),
1334                         'type' => 'Accept',
1335                         'actor' => $owner['url'],
1336                         'object' => ['id' => $id, 'type' => 'Follow',
1337                                 'actor' => $profile['url'],
1338                                 'object' => $owner['url']],
1339                         'instrument' => ['type' => 'Service', 'name' => BaseObject::getApp()->getUserAgent()],
1340                         'to' => [$profile['url']]];
1341
1342                 Logger::log('Sending accept to ' . $target . ' for user ' . $uid . ' with id ' . $id, Logger::DEBUG);
1343
1344                 $signed = LDSignature::sign($data, $owner);
1345                 HTTPSignature::transmit($signed, $profile['inbox'], $uid);
1346         }
1347
1348         /**
1349          * Reject a contact request or terminates the contact relation
1350          *
1351          * @param string  $target Target profile
1352          * @param         $id
1353          * @param integer $uid    User ID
1354          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1355          * @throws \ImagickException
1356          */
1357         public static function sendContactReject($target, $id, $uid)
1358         {
1359                 $profile = APContact::getByURL($target);
1360
1361                 $owner = User::getOwnerDataById($uid);
1362                 $data = ['@context' => ActivityPub::CONTEXT,
1363                         'id' => System::baseUrl() . '/activity/' . System::createGUID(),
1364                         'type' => 'Reject',
1365                         'actor' => $owner['url'],
1366                         'object' => ['id' => $id, 'type' => 'Follow',
1367                                 'actor' => $profile['url'],
1368                                 'object' => $owner['url']],
1369                         'instrument' => ['type' => 'Service', 'name' => BaseObject::getApp()->getUserAgent()],
1370                         'to' => [$profile['url']]];
1371
1372                 Logger::log('Sending reject to ' . $target . ' for user ' . $uid . ' with id ' . $id, Logger::DEBUG);
1373
1374                 $signed = LDSignature::sign($data, $owner);
1375                 HTTPSignature::transmit($signed, $profile['inbox'], $uid);
1376         }
1377
1378         /**
1379          * Transmits a message that we don't want to follow this contact anymore
1380          *
1381          * @param string  $target Target profile
1382          * @param integer $uid    User ID
1383          * @throws \Friendica\Network\HTTPException\InternalServerErrorException
1384          * @throws \ImagickException
1385          * @throws \Exception
1386          */
1387         public static function sendContactUndo($target, $cid, $uid)
1388         {
1389                 $profile = APContact::getByURL($target);
1390
1391                 $object_id = self::activityIDFromContact($cid);
1392                 if (empty($object_id)) {
1393                         return;
1394                 }
1395
1396                 $id = System::baseUrl() . '/activity/' . System::createGUID();
1397
1398                 $owner = User::getOwnerDataById($uid);
1399                 $data = ['@context' => ActivityPub::CONTEXT,
1400                         'id' => $id,
1401                         'type' => 'Undo',
1402                         'actor' => $owner['url'],
1403                         'object' => ['id' => $object_id, 'type' => 'Follow',
1404                                 'actor' => $owner['url'],
1405                                 'object' => $profile['url']],
1406                         'instrument' => ['type' => 'Service', 'name' => BaseObject::getApp()->getUserAgent()],
1407                         'to' => [$profile['url']]];
1408
1409                 Logger::log('Sending undo to ' . $target . ' for user ' . $uid . ' with id ' . $id, Logger::DEBUG);
1410
1411                 $signed = LDSignature::sign($data, $owner);
1412                 HTTPSignature::transmit($signed, $profile['inbox'], $uid);
1413         }
1414 }