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