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