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