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