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