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