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