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