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