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