]> git.mxchange.org Git - friendica.git/blob - src/Protocol/ActivityPub/Transmitter.php
AP: We now transmit and process events
[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                                 }
286                                 if (!in_array($receiver, $exclude)) {
287                                         $permissions[$element][] = $receiver;
288                                 }
289                         }
290                 }
291                 return $permissions;
292         }
293
294         /**
295          * Creates an array of permissions from an item thread
296          *
297          * @param array $item
298          * @param boolean $blindcopy
299          *
300          * @return array with permission data
301          */
302         private static function createPermissionBlockForItem($item, $blindcopy)
303         {
304                 // Will be activated in a later step
305                 // $networks = [Protocol::ACTIVITYPUB, Protocol::DFRN, Protocol::DIASPORA, Protocol::OSTATUS];
306
307                 // For now only send to these contacts:
308                 $networks = [Protocol::ACTIVITYPUB, Protocol::OSTATUS];
309
310                 $data = ['to' => [], 'cc' => [], 'bcc' => []];
311
312                 $data = array_merge($data, self::fetchPermissionBlockFromConversation($item));
313
314                 $actor_profile = APContact::getByURL($item['author-link']);
315
316                 $terms = Term::tagArrayFromItemId($item['id'], TERM_MENTION);
317
318                 if (!$item['private']) {
319                         $data['to'][] = ActivityPub::PUBLIC_COLLECTION;
320                         if (!empty($actor_profile['followers'])) {
321                                 $data['cc'][] = $actor_profile['followers'];
322                         }
323
324                         foreach ($terms as $term) {
325                                 $profile = APContact::getByURL($term['url'], false);
326                                 if (!empty($profile)) {
327                                         $data['to'][] = $profile['url'];
328                                 }
329                         }
330                 } else {
331                         $receiver_list = Item::enumeratePermissions($item);
332
333                         $mentioned = [];
334
335                         foreach ($terms as $term) {
336                                 $cid = Contact::getIdForURL($term['url'], $item['uid']);
337                                 if (!empty($cid) && in_array($cid, $receiver_list)) {
338                                         $contact = DBA::selectFirst('contact', ['url'], ['id' => $cid, 'network' => $networks]);
339                                         if (DBA::isResult($contact) && !empty($profile = APContact::getByURL($contact['url'], false))) {
340                                                 $data['to'][] = $profile['url'];
341                                         }
342                                 }
343                         }
344
345                         foreach ($receiver_list as $receiver) {
346                                 $contact = DBA::selectFirst('contact', ['url'], ['id' => $receiver, 'network' => $networks]);
347                                 if (DBA::isResult($contact) && !empty($profile = APContact::getByURL($contact['url'], false))) {
348                                         // BCC is currently deactivated, due to Pleroma and Mastodon not reacting like expected
349                                         // $data['bcc'][] = $profile['url'];
350                                         $data['cc'][] = $profile['url'];
351                                 }
352                         }
353                 }
354
355                 $parents = Item::select(['id', 'author-link', 'owner-link', 'gravity', 'uri'], ['parent' => $item['parent']]);
356                 while ($parent = Item::fetch($parents)) {
357                         // Don't include data from future posts
358                         if ($parent['id'] >= $item['id']) {
359                                 continue;
360                         }
361
362                         $profile = APContact::getByURL($parent['author-link'], false);
363                         if (!empty($profile)) {
364                                 if ($parent['uri'] == $item['thr-parent']) {
365                                         $data['to'][] = $profile['url'];
366                                 } else {
367                                         $data['cc'][] = $profile['url'];
368                                 }
369                         }
370
371                         if ($item['gravity'] != GRAVITY_PARENT) {
372                                 continue;
373                         }
374
375                         $profile = APContact::getByURL($parent['owner-link'], false);
376                         if (!empty($profile)) {
377                                 $data['cc'][] = $profile['url'];
378                         }
379                 }
380                 DBA::close($parents);
381
382                 $data['to'] = array_unique($data['to']);
383                 $data['cc'] = array_unique($data['cc']);
384                 $data['bcc'] = array_unique($data['bcc']);
385
386                 if (($key = array_search($item['author-link'], $data['to'])) !== false) {
387                         unset($data['to'][$key]);
388                 }
389
390                 if (($key = array_search($item['author-link'], $data['cc'])) !== false) {
391                         unset($data['cc'][$key]);
392                 }
393
394                 if (($key = array_search($item['author-link'], $data['bcc'])) !== false) {
395                         unset($data['bcc'][$key]);
396                 }
397
398                 foreach ($data['to'] as $to) {
399                         if (($key = array_search($to, $data['cc'])) !== false) {
400                                 unset($data['cc'][$key]);
401                         }
402
403                         if (($key = array_search($to, $data['bcc'])) !== false) {
404                                 unset($data['bcc'][$key]);
405                         }
406                 }
407
408                 foreach ($data['cc'] as $cc) {
409                         if (($key = array_search($cc, $data['bcc'])) !== false) {
410                                 unset($data['bcc'][$key]);
411                         }
412                 }
413
414                 $receivers = ['to' => array_values($data['to']), 'cc' => array_values($data['cc']), 'bcc' => array_values($data['bcc'])];
415
416                 if (!$blindcopy) {
417                         unset($receivers['bcc']);
418                 }
419
420                 return $receivers;
421         }
422
423         /**
424          * Fetches a list of inboxes of followers of a given user
425          *
426          * @param integer $uid User ID
427          * @param boolean $personal fetch personal inboxes
428          *
429          * @return array of follower inboxes
430          */
431         public static function fetchTargetInboxesforUser($uid, $personal = false)
432         {
433                 $inboxes = [];
434
435                 // Will be activated in a later step
436                 // $networks = [Protocol::ACTIVITYPUB, Protocol::DFRN, Protocol::DIASPORA, Protocol::OSTATUS];
437
438                 // For now only send to these contacts:
439                 $networks = [Protocol::ACTIVITYPUB, Protocol::OSTATUS];
440
441                 $condition = ['uid' => $uid, 'network' => $networks, 'archive' => false, 'pending' => false];
442
443                 if (!empty($uid)) {
444                         $condition['rel'] = [Contact::FOLLOWER, Contact::FRIEND];
445                 }
446
447                 $contacts = DBA::select('contact', ['url'], $condition);
448                 while ($contact = DBA::fetch($contacts)) {
449                         $profile = APContact::getByURL($contact['url'], false);
450                         if (!empty($profile)) {
451                                 if (empty($profile['sharedinbox']) || $personal) {
452                                         $target = $profile['inbox'];
453                                 } else {
454                                         $target = $profile['sharedinbox'];
455                                 }
456                                 $inboxes[$target] = $target;
457                         }
458                 }
459                 DBA::close($contacts);
460
461                 return $inboxes;
462         }
463
464         /**
465          * Fetches an array of inboxes for the given item and user
466          *
467          * @param array $item
468          * @param integer $uid User ID
469          * @param boolean $personal fetch personal inboxes
470          *
471          * @return array with inboxes
472          */
473         public static function fetchTargetInboxes($item, $uid, $personal = false)
474         {
475                 $permissions = self::createPermissionBlockForItem($item, true);
476                 if (empty($permissions)) {
477                         return [];
478                 }
479
480                 $inboxes = [];
481
482                 if ($item['gravity'] == GRAVITY_ACTIVITY) {
483                         $item_profile = APContact::getByURL($item['author-link'], false);
484                 } else {
485                         $item_profile = APContact::getByURL($item['owner-link'], false);
486                 }
487
488                 foreach (['to', 'cc', 'bto', 'bcc'] as $element) {
489                         if (empty($permissions[$element])) {
490                                 continue;
491                         }
492
493                         $blindcopy = in_array($element, ['bto', 'bcc']);
494
495                         foreach ($permissions[$element] as $receiver) {
496                                 if ($receiver == $item_profile['followers']) {
497                                         $inboxes = array_merge($inboxes, self::fetchTargetInboxesforUser($uid, $personal));
498                                 } else {
499                                         $profile = APContact::getByURL($receiver, false);
500                                         if (!empty($profile)) {
501                                                 if (empty($profile['sharedinbox']) || $personal || $blindcopy) {
502                                                         $target = $profile['inbox'];
503                                                 } else {
504                                                         $target = $profile['sharedinbox'];
505                                                 }
506                                                 $inboxes[$target] = $target;
507                                         }
508                                 }
509                         }
510                 }
511
512                 return $inboxes;
513         }
514
515         /**
516          * Returns the activity type of a given item
517          *
518          * @param array $item
519          *
520          * @return string with activity type
521          */
522         private static function getTypeOfItem($item)
523         {
524                 if (!empty(Diaspora::isReshare($item['body'], false))) {
525                         $type = 'Announce';
526                 } elseif ($item['verb'] == ACTIVITY_POST) {
527                         if ($item['created'] == $item['edited']) {
528                                 $type = 'Create';
529                         } else {
530                                 $type = 'Update';
531                         }
532                 } elseif ($item['verb'] == ACTIVITY_LIKE) {
533                         $type = 'Like';
534                 } elseif ($item['verb'] == ACTIVITY_DISLIKE) {
535                         $type = 'Dislike';
536                 } elseif ($item['verb'] == ACTIVITY_ATTEND) {
537                         $type = 'Accept';
538                 } elseif ($item['verb'] == ACTIVITY_ATTENDNO) {
539                         $type = 'Reject';
540                 } elseif ($item['verb'] == ACTIVITY_ATTENDMAYBE) {
541                         $type = 'TentativeAccept';
542                 } else {
543                         $type = '';
544                 }
545
546                 return $type;
547         }
548
549         /**
550          * Creates the activity or fetches it from the cache
551          *
552          * @param integer $item_id
553          *
554          * @return array with the activity
555          */
556         public static function createCachedActivityFromItem($item_id)
557         {
558                 $cachekey = 'APDelivery:createActivity:' . $item_id;
559                 $data = Cache::get($cachekey);
560                 if (!is_null($data)) {
561                         return $data;
562                 }
563
564                 $data = ActivityPub\Transmitter::createActivityFromItem($item_id);
565
566                 Cache::set($cachekey, $data, Cache::QUARTER_HOUR);
567                 return $data;
568         }
569
570         /**
571          * Creates an activity array for a given item id
572          *
573          * @param integer $item_id
574          * @param boolean $object_mode Is the activity item is used inside another object?
575          *
576          * @return array of activity
577          */
578         public static function createActivityFromItem($item_id, $object_mode = false)
579         {
580                 $item = Item::selectFirst([], ['id' => $item_id, 'parent-network' => Protocol::NATIVE_SUPPORT]);
581
582                 if (!DBA::isResult($item)) {
583                         return false;
584                 }
585
586                 $condition = ['item-uri' => $item['uri'], 'protocol' => Conversation::PARCEL_ACTIVITYPUB];
587                 $conversation = DBA::selectFirst('conversation', ['source'], $condition);
588                 if (DBA::isResult($conversation)) {
589                         $data = json_decode($conversation['source']);
590                         if (!empty($data)) {
591                                 return $data;
592                         }
593                 }
594
595                 $type = self::getTypeOfItem($item);
596
597                 if (!$object_mode) {
598                         $data = ['@context' => ActivityPub::CONTEXT];
599
600                         if ($item['deleted'] && ($item['gravity'] == GRAVITY_ACTIVITY)) {
601                                 $type = 'Undo';
602                         } elseif ($item['deleted']) {
603                                 $type = 'Delete';
604                         }
605                 } else {
606                         $data = [];
607                 }
608
609                 $data['id'] = $item['uri'] . '#' . $type;
610                 $data['type'] = $type;
611                 $data['actor'] = $item['owner-link'];
612
613                 $data['published'] = DateTimeFormat::utc($item['created'] . '+00:00', DateTimeFormat::ATOM);
614
615                 $data['instrument'] = ['type' => 'Service', 'name' => BaseObject::getApp()->getUserAgent()];
616
617                 $data = array_merge($data, self::createPermissionBlockForItem($item, false));
618
619                 if (in_array($data['type'], ['Create', 'Update', 'Delete'])) {
620                         $data['object'] = self::createNote($item);
621                 } elseif ($data['type'] == 'Announce') {
622                         $data['object'] = self::createAnnounce($item);
623                 } elseif ($data['type'] == 'Undo') {
624                         $data['object'] = self::createActivityFromItem($item_id, true);
625                 } else {
626                         $data['diaspora:guid'] = $item['guid'];
627                         $data['object'] = $item['thr-parent'];
628                 }
629
630                 $owner = User::getOwnerDataById($item['uid']);
631
632                 if (!$object_mode) {
633                         return LDSignature::sign($data, $owner);
634                 } else {
635                         return $data;
636                 }
637
638                 /// @todo Create "conversation" entry
639         }
640
641         /**
642          * Creates an object array for a given item id
643          *
644          * @param integer $item_id
645          *
646          * @return array with the object data
647          */
648         public static function createObjectFromItemID($item_id)
649         {
650                 $item = Item::selectFirst([], ['id' => $item_id, 'parent-network' => Protocol::NATIVE_SUPPORT]);
651
652                 if (!DBA::isResult($item)) {
653                         return false;
654                 }
655
656                 $data = ['@context' => ActivityPub::CONTEXT];
657                 $data = array_merge($data, self::createNote($item));
658
659                 return $data;
660         }
661
662         /**
663          * Creates a location entry for a given item array
664          *
665          * @param array $item
666          *
667          * @return array with location array
668          */
669         private static function createLocation($item)
670         {
671                 $location = ['type' => 'Place'];
672
673                 if (!empty($item['location'])) {
674                         $location['name'] = $item['location'];
675                 }
676
677                 $coord = [];
678
679                 if (empty($item['coord'])) {
680                         $coord = Map::getCoordinates($item['location']);
681                 } else {
682                         $coords = explode(' ', $item['coord']);
683                         if (count($coords) == 2) {
684                                 $coord = ['lat' => $coords[0], 'lon' => $coords[1]];
685                         }
686                 }
687
688                 if (!empty($coord['lat']) && !empty($coord['lon'])) {
689                         $location['latitude'] = $coord['lat'];
690                         $location['longitude'] = $coord['lon'];
691                 }
692
693                 return $location;
694         }
695
696         /**
697          * Returns a tag array for a given item array
698          *
699          * @param array $item
700          *
701          * @return array of tags
702          */
703         private static function createTagList($item)
704         {
705                 $tags = [];
706
707                 $terms = Term::tagArrayFromItemId($item['id']);
708                 foreach ($terms as $term) {
709                         if ($term['type'] == TERM_HASHTAG) {
710                                 $tags[] = ['type' => 'Hashtag', 'href' => $term['url'], 'name' => '#' . $term['term']];
711                         } elseif ($term['type'] == TERM_MENTION) {
712                                 $contact = Contact::getDetailsByURL($term['url']);
713                                 if (!empty($contact['addr'])) {
714                                         $mention = '@' . $contact['addr'];
715                                 } else {
716                                         $mention = '@' . $term['url'];
717                                 }
718
719                                 $tags[] = ['type' => 'Mention', 'href' => $term['url'], 'name' => $mention];
720                         }
721                 }
722                 return $tags;
723         }
724
725         /**
726          * Adds attachment data to the JSON document
727          *
728          * @param array $item Data of the item that is to be posted
729          * @param text $type Object type
730          *
731          * @return array with attachment data
732          */
733         private static function createAttachmentList($item, $type)
734         {
735                 $attachments = [];
736
737                 $arr = explode('[/attach],', $item['attach']);
738                 if (count($arr)) {
739                         foreach ($arr as $r) {
740                                 $matches = false;
741                                 $cnt = preg_match('|\[attach\]href=\"(.*?)\" length=\"(.*?)\" type=\"(.*?)\" title=\"(.*?)\"|', $r, $matches);
742                                 if ($cnt) {
743                                         $attributes = ['type' => 'Document',
744                                                         'mediaType' => $matches[3],
745                                                         'url' => $matches[1],
746                                                         'name' => null];
747
748                                         if (trim($matches[4]) != '') {
749                                                 $attributes['name'] = trim($matches[4]);
750                                         }
751
752                                         $attachments[] = $attributes;
753                                 }
754                         }
755                 }
756
757                 if ($type != 'Note') {
758                         return $attachments;
759                 }
760
761                 // Simplify image codes
762                 $body = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '[img]$3[/img]', $item['body']);
763
764                 // Grab all pictures and create attachments out of them
765                 if (preg_match_all("/\[img\]([^\[\]]*)\[\/img\]/Usi", $body, $pictures)) {
766                         foreach ($pictures[1] as $picture) {
767                                 $imgdata = Image::getInfoFromURL($picture);
768                                 if ($imgdata) {
769                                         $attachments[] = ['type' => 'Document',
770                                                 'mediaType' => $imgdata['mime'],
771                                                 'url' => $picture,
772                                                 'name' => null];
773                                 }
774                         }
775                 }
776
777                 return $attachments;
778         }
779
780         /**
781          * @brief Callback function to replace a Friendica style mention in a mention that is used on AP
782          *
783          * @param array $match Matching values for the callback
784          * @return string Replaced mention
785          */
786         private static function mentionCallback($match)
787         {
788                 if (empty($match[1])) {
789                         return;
790                 }
791
792                 $data = Contact::getDetailsByURL($match[1]);
793                 if (empty($data) || empty($data['nick'])) {
794                         return;
795                 }
796
797                 return '@[url=' . $data['url'] . ']' . $data['nick'] . '[/url]';
798         }
799
800         /**
801          * Remove image elements and replaces them with links to the image
802          *
803          * @param string $body
804          *
805          * @return string with replaced elements
806          */
807         private static function removePictures($body)
808         {
809                 // Simplify image codes
810                 $body = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '[img]$3[/img]', $body);
811
812                 $body = preg_replace("/\[url=([^\[\]]*)\]\[img\](.*)\[\/img\]\[\/url\]/Usi", '[url]$1[/url]', $body);
813                 $body = preg_replace("/\[img\]([^\[\]]*)\[\/img\]/Usi", '[url]$1[/url]', $body);
814
815                 return $body;
816         }
817
818         /**
819          * Fetches the "context" value for a givem item array from the "conversation" table
820          *
821          * @param array $item
822          *
823          * @return string with context url
824          */
825         private static function fetchContextURLForItem($item)
826         {
827                 $conversation = DBA::selectFirst('conversation', ['conversation-href', 'conversation-uri'], ['item-uri' => $item['parent-uri']]);
828                 if (DBA::isResult($conversation) && !empty($conversation['conversation-href'])) {
829                         $context_uri = $conversation['conversation-href'];
830                 } elseif (DBA::isResult($conversation) && !empty($conversation['conversation-uri'])) {
831                         $context_uri = $conversation['conversation-uri'];
832                 } else {
833                         $context_uri = $item['parent-uri'] . '#context';
834                 }
835                 return $context_uri;
836         }
837
838         /**
839          * Returns if the post contains sensitive content ("nsfw")
840          *
841          * @param integer $item_id
842          *
843          * @return boolean
844          */
845         private static function isSensitive($item_id)
846         {
847                 $condition = ['otype' => TERM_OBJ_POST, 'oid' => $item_id, 'type' => TERM_HASHTAG, 'term' => 'nsfw'];
848                 return DBA::exists('term', $condition);
849         }
850
851         /**
852          * Creates event data
853          *
854          * @param array $item
855          *
856          * @return array with the event data
857          */
858         public static function createEvent($item)
859         {
860                 $event = [];
861                 $event['name'] = $item['event-summary'];
862                 $event['content'] = BBCode::convert($item['event-desc'], false, 7);
863                 $event['startTime'] = DateTimeFormat::utc($item['event-start'] . '+00:00', DateTimeFormat::ATOM);
864
865                 if (!$item['event-nofinish']) {
866                         $event['endTime'] = DateTimeFormat::utc($item['event-finish'] . '+00:00', DateTimeFormat::ATOM);
867                 }
868
869                 if (!empty($item['event-location'])) {
870                         $item['location'] = $item['event-location'];
871                         $event['location'] = self::createLocation($item);
872                 }
873
874                 return $event;
875         }
876
877         /**
878          * Creates a note/article object array
879          *
880          * @param array $item
881          *
882          * @return array with the object data
883          */
884         public static function createNote($item)
885         {
886                 if ($item['event-type'] == 'event') {
887                         $type = 'Event';
888                 } elseif (!empty($item['title'])) {
889                         $type = 'Article';
890                 } else {
891                         $type = 'Note';
892                 }
893
894                 if ($item['deleted']) {
895                         $type = 'Tombstone';
896                 }
897
898                 $data = [];
899                 $data['id'] = $item['uri'];
900                 $data['type'] = $type;
901
902                 if ($item['deleted']) {
903                         return $data;
904                 }
905
906                 $data['summary'] = null; // Ignore by now
907
908                 if ($item['uri'] != $item['thr-parent']) {
909                         $data['inReplyTo'] = $item['thr-parent'];
910                 } else {
911                         $data['inReplyTo'] = null;
912                 }
913
914                 $data['diaspora:guid'] = $item['guid'];
915                 $data['published'] = DateTimeFormat::utc($item['created'] . '+00:00', DateTimeFormat::ATOM);
916
917                 if ($item['created'] != $item['edited']) {
918                         $data['updated'] = DateTimeFormat::utc($item['edited'] . '+00:00', DateTimeFormat::ATOM);
919                 }
920
921                 $data['url'] = $item['plink'];
922                 $data['attributedTo'] = $item['author-link'];
923                 $data['sensitive'] = self::isSensitive($item['id']);
924                 $data['context'] = self::fetchContextURLForItem($item);
925
926                 if (!empty($item['title'])) {
927                         $data['name'] = BBCode::toPlaintext($item['title'], false);
928                 }
929
930                 $body = $item['body'];
931
932                 if ($type == 'Note') {
933                         $body = self::removePictures($body);
934                 }
935
936                 if ($type == 'Event') {
937                         $data = array_merge($data, self::createEvent($item));
938                 } else {
939                         $regexp = "/[@!]\[url\=([^\[\]]*)\].*?\[\/url\]/ism";
940                         $body = preg_replace_callback($regexp, ['self', 'mentionCallback'], $body);
941
942                         $data['content'] = BBCode::convert($body, false, 7);
943                 }
944
945                 $data['source'] = ['content' => $item['body'], 'mediaType' => "text/bbcode"];
946
947                 if (!empty($item['signed_text']) && ($item['uri'] != $item['thr-parent'])) {
948                         $data['diaspora:comment'] = $item['signed_text'];
949                 }
950
951                 $data['attachment'] = self::createAttachmentList($item, $type);
952                 $data['tag'] = self::createTagList($item);
953
954                 if (empty($data['location']) && (!empty($item['coord']) || !empty($item['location']))) {
955                         $data['location'] = self::createLocation($item);
956                 }
957
958                 if (!empty($item['app'])) {
959                         $data['generator'] = ['type' => 'Application', 'name' => $item['app']];
960                 }
961
962                 $data = array_merge($data, self::createPermissionBlockForItem($item, false));
963
964                 return $data;
965         }
966
967         /**
968          * Creates an announce object entry
969          *
970          * @param array $item
971          *
972          * @return string with announced object url
973          */
974         public static function createAnnounce($item)
975         {
976                 $announce = api_share_as_retweet($item);
977                 if (empty($announce['plink'])) {
978                         return self::createNote($item);
979                 }
980
981                 return $announce['plink'];
982         }
983
984         /**
985          * Transmits a contact suggestion to a given inbox
986          *
987          * @param integer $uid User ID
988          * @param string $inbox Target inbox
989          * @param integer $suggestion_id Suggestion ID
990          *
991          * @return boolean was the transmission successful?
992          */
993         public static function sendContactSuggestion($uid, $inbox, $suggestion_id)
994         {
995                 $owner = User::getOwnerDataById($uid);
996                 $profile = APContact::getByURL($owner['url']);
997
998                 $suggestion = DBA::selectFirst('fsuggest', ['url', 'note', 'created'], ['id' => $suggestion_id]);
999
1000                 $data = ['@context' => 'https://www.w3.org/ns/activitystreams',
1001                         'id' => System::baseUrl() . '/activity/' . System::createGUID(),
1002                         'type' => 'Announce',
1003                         'actor' => $owner['url'],
1004                         'object' => $suggestion['url'],
1005                         'content' => $suggestion['note'],
1006                         'instrument' => ['type' => 'Service', 'name' => BaseObject::getApp()->getUserAgent()],
1007                         'to' => [ActivityPub::PUBLIC_COLLECTION],
1008                         'cc' => []];
1009
1010                 $signed = LDSignature::sign($data, $owner);
1011
1012                 logger('Deliver profile deletion for user ' . $uid . ' to ' . $inbox . ' via ActivityPub', LOGGER_DEBUG);
1013                 return HTTPSignature::transmit($signed, $inbox, $uid);
1014         }
1015
1016         /**
1017          * Transmits a profile deletion to a given inbox
1018          *
1019          * @param integer $uid User ID
1020          * @param string $inbox Target inbox
1021          *
1022          * @return boolean was the transmission successful?
1023          */
1024         public static function sendProfileDeletion($uid, $inbox)
1025         {
1026                 $owner = User::getOwnerDataById($uid);
1027                 $profile = APContact::getByURL($owner['url']);
1028
1029                 $data = ['@context' => 'https://www.w3.org/ns/activitystreams',
1030                         'id' => System::baseUrl() . '/activity/' . System::createGUID(),
1031                         'type' => 'Delete',
1032                         'actor' => $owner['url'],
1033                         'object' => $owner['url'],
1034                         'published' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
1035                         'instrument' => ['type' => 'Service', 'name' => BaseObject::getApp()->getUserAgent()],
1036                         'to' => [ActivityPub::PUBLIC_COLLECTION],
1037                         'cc' => []];
1038
1039                 $signed = LDSignature::sign($data, $owner);
1040
1041                 logger('Deliver profile deletion for user ' . $uid . ' to ' . $inbox . ' via ActivityPub', LOGGER_DEBUG);
1042                 return HTTPSignature::transmit($signed, $inbox, $uid);
1043         }
1044
1045         /**
1046          * Transmits a profile change to a given inbox
1047          *
1048          * @param integer $uid User ID
1049          * @param string $inbox Target inbox
1050          *
1051          * @return boolean was the transmission successful?
1052          */
1053         public static function sendProfileUpdate($uid, $inbox)
1054         {
1055                 $owner = User::getOwnerDataById($uid);
1056                 $profile = APContact::getByURL($owner['url']);
1057
1058                 $data = ['@context' => 'https://www.w3.org/ns/activitystreams',
1059                         'id' => System::baseUrl() . '/activity/' . System::createGUID(),
1060                         'type' => 'Update',
1061                         'actor' => $owner['url'],
1062                         'object' => self::getProfile($uid),
1063                         'published' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
1064                         'instrument' => ['type' => 'Service', 'name' => BaseObject::getApp()->getUserAgent()],
1065                         'to' => [$profile['followers']],
1066                         'cc' => []];
1067
1068                 $signed = LDSignature::sign($data, $owner);
1069
1070                 logger('Deliver profile update for user ' . $uid . ' to ' . $inbox . ' via ActivityPub', LOGGER_DEBUG);
1071                 return HTTPSignature::transmit($signed, $inbox, $uid);
1072         }
1073
1074         /**
1075          * Transmits a given activity to a target
1076          *
1077          * @param array $activity
1078          * @param string $target Target profile
1079          * @param integer $uid User ID
1080          */
1081         public static function sendActivity($activity, $target, $uid)
1082         {
1083                 $profile = APContact::getByURL($target);
1084
1085                 $owner = User::getOwnerDataById($uid);
1086
1087                 $data = ['@context' => 'https://www.w3.org/ns/activitystreams',
1088                         'id' => System::baseUrl() . '/activity/' . System::createGUID(),
1089                         'type' => $activity,
1090                         'actor' => $owner['url'],
1091                         'object' => $profile['url'],
1092                         'instrument' => ['type' => 'Service', 'name' => BaseObject::getApp()->getUserAgent()],
1093                         'to' => $profile['url']];
1094
1095                 logger('Sending activity ' . $activity . ' to ' . $target . ' for user ' . $uid, LOGGER_DEBUG);
1096
1097                 $signed = LDSignature::sign($data, $owner);
1098                 HTTPSignature::transmit($signed, $profile['inbox'], $uid);
1099         }
1100
1101         /**
1102          * Transmit a message that the contact request had been accepted
1103          *
1104          * @param string $target Target profile
1105          * @param $id
1106          * @param integer $uid User ID
1107          */
1108         public static function sendContactAccept($target, $id, $uid)
1109         {
1110                 $profile = APContact::getByURL($target);
1111
1112                 $owner = User::getOwnerDataById($uid);
1113                 $data = ['@context' => 'https://www.w3.org/ns/activitystreams',
1114                         'id' => System::baseUrl() . '/activity/' . System::createGUID(),
1115                         'type' => 'Accept',
1116                         'actor' => $owner['url'],
1117                         'object' => ['id' => $id, 'type' => 'Follow',
1118                                 'actor' => $profile['url'],
1119                                 'object' => $owner['url']],
1120                         'instrument' => ['type' => 'Service', 'name' => BaseObject::getApp()->getUserAgent()],
1121                         'to' => $profile['url']];
1122
1123                 logger('Sending accept to ' . $target . ' for user ' . $uid . ' with id ' . $id, LOGGER_DEBUG);
1124
1125                 $signed = LDSignature::sign($data, $owner);
1126                 HTTPSignature::transmit($signed, $profile['inbox'], $uid);
1127         }
1128
1129         /**
1130          * Reject a contact request or terminates the contact relation
1131          *
1132          * @param string $target Target profile
1133          * @param $id
1134          * @param integer $uid User ID
1135          */
1136         public static function sendContactReject($target, $id, $uid)
1137         {
1138                 $profile = APContact::getByURL($target);
1139
1140                 $owner = User::getOwnerDataById($uid);
1141                 $data = ['@context' => 'https://www.w3.org/ns/activitystreams',
1142                         'id' => System::baseUrl() . '/activity/' . System::createGUID(),
1143                         'type' => 'Reject',
1144                         'actor' => $owner['url'],
1145                         'object' => ['id' => $id, 'type' => 'Follow',
1146                                 'actor' => $profile['url'],
1147                                 'object' => $owner['url']],
1148                         'instrument' => ['type' => 'Service', 'name' => BaseObject::getApp()->getUserAgent()],
1149                         'to' => $profile['url']];
1150
1151                 logger('Sending reject to ' . $target . ' for user ' . $uid . ' with id ' . $id, LOGGER_DEBUG);
1152
1153                 $signed = LDSignature::sign($data, $owner);
1154                 HTTPSignature::transmit($signed, $profile['inbox'], $uid);
1155         }
1156
1157         /**
1158          * Transmits a message that we don't want to follow this contact anymore
1159          *
1160          * @param string $target Target profile
1161          * @param integer $uid User ID
1162          */
1163         public static function sendContactUndo($target, $uid)
1164         {
1165                 $profile = APContact::getByURL($target);
1166
1167                 $id = System::baseUrl() . '/activity/' . System::createGUID();
1168
1169                 $owner = User::getOwnerDataById($uid);
1170                 $data = ['@context' => 'https://www.w3.org/ns/activitystreams',
1171                         'id' => $id,
1172                         'type' => 'Undo',
1173                         'actor' => $owner['url'],
1174                         'object' => ['id' => $id, 'type' => 'Follow',
1175                                 'actor' => $owner['url'],
1176                                 'object' => $profile['url']],
1177                         'instrument' => ['type' => 'Service', 'name' => BaseObject::getApp()->getUserAgent()],
1178                         'to' => $profile['url']];
1179
1180                 logger('Sending undo to ' . $target . ' for user ' . $uid . ' with id ' . $id, LOGGER_DEBUG);
1181
1182                 $signed = LDSignature::sign($data, $owner);
1183                 HTTPSignature::transmit($signed, $profile['inbox'], $uid);
1184         }
1185 }