]> git.mxchange.org Git - friendica.git/blob - src/Protocol/ActivityPub/Transmitter.php
76c233fd5ecc09e3b20f6cda61d3894e5e79237e
[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\Database\DBA;
8 use Friendica\Core\System;
9 use Friendica\BaseObject;
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\Protocol\ActivityPub;
23 use Friendica\Model\Profile;
24 use Friendica\Core\Config;
25 use Friendica\Object\Image;
26
27 /**
28  * @brief ActivityPub Transmitter Protocol class
29  *
30  * To-Do:
31  * - Event
32  *
33  * Complicated:
34  * - Announce
35  * - Undo Announce
36  *
37  * General:
38  * - Queueing unsucessful deliveries
39  */
40 class Transmitter
41 {
42         /**
43          * @brief 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          * @brief 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          * @brief 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' => $owner['uid'], 'contact-id' => $owner['id'], 'author-id' => $public_contact,
149                         'wall' => true, '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 profile array
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'];
207                 $contact = DBA::selectFirst('contact', $fields, ['uid' => $uid, 'self' => true]);
208                 if (!DBA::isResult($contact)) {
209                         return [];
210                 }
211
212                 $data = ['@context' => ActivityPub::CONTEXT];
213                 $data['id'] = $contact['url'];
214                 $data['diaspora:guid'] = $user['guid'];
215                 $data['type'] = ActivityPub::ACCOUNT_TYPES[$user['account-type']];
216                 $data['following'] = System::baseUrl() . '/following/' . $user['nickname'];
217                 $data['followers'] = System::baseUrl() . '/followers/' . $user['nickname'];
218                 $data['inbox'] = System::baseUrl() . '/inbox/' . $user['nickname'];
219                 $data['outbox'] = System::baseUrl() . '/outbox/' . $user['nickname'];
220                 $data['preferredUsername'] = $user['nickname'];
221                 $data['name'] = $contact['name'];
222                 $data['vcard:hasAddress'] = ['@type' => 'vcard:Home', 'vcard:country-name' => $profile['country-name'],
223                         'vcard:region' => $profile['region'], 'vcard:locality' => $profile['locality']];
224                 $data['summary'] = $contact['about'];
225                 $data['url'] = $contact['url'];
226                 $data['manuallyApprovesFollowers'] = in_array($user['page-flags'], [Contact::PAGE_NORMAL, Contact::PAGE_PRVGROUP]);
227                 $data['publicKey'] = ['id' => $contact['url'] . '#main-key',
228                         'owner' => $contact['url'],
229                         'publicKeyPem' => $user['pubkey']];
230                 $data['endpoints'] = ['sharedInbox' => System::baseUrl() . '/inbox'];
231                 $data['icon'] = ['type' => 'Image',
232                         'url' => $contact['avatar']];
233
234                 // tags: https://kitty.town/@inmysocks/100656097926961126.json
235                 return $data;
236         }
237
238         /**
239          * @brief Returns an array with permissions of a given item array
240          *
241          * @param array $item
242          *
243          * @return array with permissions
244          */
245         private static function fetchPermissionBlockFromConversation($item)
246         {
247                 if (empty($item['thr-parent'])) {
248                         return [];
249                 }
250
251                 $condition = ['item-uri' => $item['thr-parent'], 'protocol' => Conversation::PARCEL_ACTIVITYPUB];
252                 $conversation = DBA::selectFirst('conversation', ['source'], $condition);
253                 if (!DBA::isResult($conversation)) {
254                         return [];
255                 }
256
257                 $activity = json_decode($conversation['source'], true);
258
259                 $actor = JsonLD::fetchElement($activity, 'actor', 'id');
260                 $profile = APContact::getByURL($actor);
261
262                 $item_profile = APContact::getByURL($item['author-link']);
263                 $exclude[] = $item['author-link'];
264
265                 if ($item['gravity'] == GRAVITY_PARENT) {
266                         $exclude[] = $item['owner-link'];
267                 }
268
269                 $permissions['to'][] = $actor;
270
271                 foreach (['to', 'cc', 'bto', 'bcc'] as $element) {
272                         if (empty($activity[$element])) {
273                                 continue;
274                         }
275                         if (is_string($activity[$element])) {
276                                 $activity[$element] = [$activity[$element]];
277                         }
278
279                         foreach ($activity[$element] as $receiver) {
280                                 if ($receiver == $profile['followers'] && !empty($item_profile['followers'])) {
281                                         $receiver = $item_profile['followers'];
282                                 }
283                                 if (!in_array($receiver, $exclude)) {
284                                         $permissions[$element][] = $receiver;
285                                 }
286                         }
287                 }
288                 return $permissions;
289         }
290
291         /**
292          * @brief Creates an array of permissions from an item thread
293          *
294          * @param array $item
295          *
296          * @return permission array
297          */
298         private static function createPermissionBlockForItem($item)
299         {
300                 $data = ['to' => [], 'cc' => []];
301
302                 $data = array_merge($data, self::fetchPermissionBlockFromConversation($item));
303
304                 $actor_profile = APContact::getByURL($item['author-link']);
305
306                 $terms = Term::tagArrayFromItemId($item['id'], TERM_MENTION);
307
308                 $contacts[$item['author-link']] = $item['author-link'];
309
310                 if (!$item['private']) {
311                         $data['to'][] = ActivityPub::PUBLIC_COLLECTION;
312                         if (!empty($actor_profile['followers'])) {
313                                 $data['cc'][] = $actor_profile['followers'];
314                         }
315
316                         foreach ($terms as $term) {
317                                 $profile = APContact::getByURL($term['url'], false);
318                                 if (!empty($profile) && empty($contacts[$profile['url']])) {
319                                         $data['cc'][] = $profile['url'];
320                                         $contacts[$profile['url']] = $profile['url'];
321                                 }
322                         }
323                 } else {
324                         $receiver_list = Item::enumeratePermissions($item);
325
326                         $mentioned = [];
327
328                         foreach ($terms as $term) {
329                                 $cid = Contact::getIdForURL($term['url'], $item['uid']);
330                                 if (!empty($cid) && in_array($cid, $receiver_list)) {
331                                         $contact = DBA::selectFirst('contact', ['url'], ['id' => $cid, 'network' => Protocol::ACTIVITYPUB]);
332                                         $data['to'][] = $contact['url'];
333                                         $contacts[$contact['url']] = $contact['url'];
334                                 }
335                         }
336
337                         foreach ($receiver_list as $receiver) {
338                                 $contact = DBA::selectFirst('contact', ['url'], ['id' => $receiver, 'network' => Protocol::ACTIVITYPUB]);
339                                 if (empty($contacts[$contact['url']])) {
340                                         $data['cc'][] = $contact['url'];
341                                         $contacts[$contact['url']] = $contact['url'];
342                                 }
343                         }
344                 }
345
346                 $parents = Item::select(['id', 'author-link', 'owner-link', 'gravity'], ['parent' => $item['parent']]);
347                 while ($parent = Item::fetch($parents)) {
348                         // Don't include data from future posts
349                         if ($parent['id'] >= $item['id']) {
350                                 continue;
351                         }
352
353                         $profile = APContact::getByURL($parent['author-link'], false);
354                         if (!empty($profile) && empty($contacts[$profile['url']])) {
355                                 $data['cc'][] = $profile['url'];
356                                 $contacts[$profile['url']] = $profile['url'];
357                         }
358
359                         if ($item['gravity'] != GRAVITY_PARENT) {
360                                 continue;
361                         }
362
363                         $profile = APContact::getByURL($parent['owner-link'], false);
364                         if (!empty($profile) && empty($contacts[$profile['url']])) {
365                                 $data['cc'][] = $profile['url'];
366                                 $contacts[$profile['url']] = $profile['url'];
367                         }
368                 }
369                 DBA::close($parents);
370
371                 if (empty($data['to'])) {
372                         $data['to'] = $data['cc'];
373                         $data['cc'] = [];
374                 }
375
376                 return $data;
377         }
378
379         /**
380          * @brief Fetches a list of inboxes of followers of a given user
381          *
382          * @param integer $uid User ID
383          *
384          * @return array of follower inboxes
385          */
386         public static function fetchTargetInboxesforUser($uid)
387         {
388                 $inboxes = [];
389
390                 $condition = ['uid' => $uid, 'network' => Protocol::ACTIVITYPUB, 'archive' => false, 'pending' => false];
391
392                 if (!empty($uid)) {
393                         $condition['rel'] = [Contact::FOLLOWER, Contact::FRIEND];
394                 }
395
396                 $contacts = DBA::select('contact', ['notify', 'batch'], $condition);
397                 while ($contact = DBA::fetch($contacts)) {
398                         $contact = defaults($contact, 'batch', $contact['notify']);
399                         $inboxes[$contact] = $contact;
400                 }
401                 DBA::close($contacts);
402
403                 return $inboxes;
404         }
405
406         /**
407          * @brief Fetches an array of inboxes for the given item and user
408          *
409          * @param array $item
410          * @param integer $uid User ID
411          *
412          * @return array with inboxes
413          */
414         public static function fetchTargetInboxes($item, $uid)
415         {
416                 $permissions = self::createPermissionBlockForItem($item);
417                 if (empty($permissions)) {
418                         return [];
419                 }
420
421                 $inboxes = [];
422
423                 if ($item['gravity'] == GRAVITY_ACTIVITY) {
424                         $item_profile = APContact::getByURL($item['author-link']);
425                 } else {
426                         $item_profile = APContact::getByURL($item['owner-link']);
427                 }
428
429                 foreach (['to', 'cc', 'bto', 'bcc'] as $element) {
430                         if (empty($permissions[$element])) {
431                                 continue;
432                         }
433
434                         foreach ($permissions[$element] as $receiver) {
435                                 if ($receiver == $item_profile['followers']) {
436                                         $inboxes = self::fetchTargetInboxesforUser($uid);
437                                 } else {
438                                         $profile = APContact::getByURL($receiver);
439                                         if (!empty($profile)) {
440                                                 $target = defaults($profile, 'sharedinbox', $profile['inbox']);
441                                                 $inboxes[$target] = $target;
442                                         }
443                                 }
444                         }
445                 }
446
447                 return $inboxes;
448         }
449
450         /**
451          * @brief Returns the activity type of a given item
452          *
453          * @param array $item
454          *
455          * @return activity type
456          */
457         private static function getTypeOfItem($item)
458         {
459                 if ($item['verb'] == ACTIVITY_POST) {
460                         if ($item['created'] == $item['edited']) {
461                                 $type = 'Create';
462                         } else {
463                                 $type = 'Update';
464                         }
465                 } elseif ($item['verb'] == ACTIVITY_LIKE) {
466                         $type = 'Like';
467                 } elseif ($item['verb'] == ACTIVITY_DISLIKE) {
468                         $type = 'Dislike';
469                 } elseif ($item['verb'] == ACTIVITY_ATTEND) {
470                         $type = 'Accept';
471                 } elseif ($item['verb'] == ACTIVITY_ATTENDNO) {
472                         $type = 'Reject';
473                 } elseif ($item['verb'] == ACTIVITY_ATTENDMAYBE) {
474                         $type = 'TentativeAccept';
475                 } else {
476                         $type = '';
477                 }
478
479                 return $type;
480         }
481
482         /**
483          * @brief Creates an activity array for a given item id
484          *
485          * @param integer $item_id
486          * @param boolean $object_mode Is the activity item is used inside another object?
487          *
488          * @return array of activity
489          */
490         public static function createActivityFromItem($item_id, $object_mode = false)
491         {
492                 $item = Item::selectFirst([], ['id' => $item_id, 'parent-network' => Protocol::NATIVE_SUPPORT]);
493
494                 if (!DBA::isResult($item)) {
495                         return false;
496                 }
497
498                 $condition = ['item-uri' => $item['uri'], 'protocol' => Conversation::PARCEL_ACTIVITYPUB];
499                 $conversation = DBA::selectFirst('conversation', ['source'], $condition);
500                 if (DBA::isResult($conversation)) {
501                         $data = json_decode($conversation['source']);
502                         if (!empty($data)) {
503                                 return $data;
504                         }
505                 }
506
507                 $type = self::getTypeOfItem($item);
508
509                 if (!$object_mode) {
510                         $data = ['@context' => ActivityPub::CONTEXT];
511
512                         if ($item['deleted'] && ($item['gravity'] == GRAVITY_ACTIVITY)) {
513                                 $type = 'Undo';
514                         } elseif ($item['deleted']) {
515                                 $type = 'Delete';
516                         }
517                 } else {
518                         $data = [];
519                 }
520
521                 $data['id'] = $item['uri'] . '#' . $type;
522                 $data['type'] = $type;
523                 $data['actor'] = $item['author-link'];
524
525                 $data['published'] = DateTimeFormat::utc($item["created"]."+00:00", DateTimeFormat::ATOM);
526
527                 if ($item["created"] != $item["edited"]) {
528                         $data['updated'] = DateTimeFormat::utc($item["edited"]."+00:00", DateTimeFormat::ATOM);
529                 }
530
531                 $data['context'] = self::fetchContextURLForItem($item);
532
533                 $data = array_merge($data, self::createPermissionBlockForItem($item));
534
535                 if (in_array($data['type'], ['Create', 'Update', 'Announce', 'Delete'])) {
536                         $data['object'] = self::createNote($item);
537                 } elseif ($data['type'] == 'Undo') {
538                         $data['object'] = self::createActivityFromItem($item_id, true);
539                 } else {
540                         $data['object'] = $item['thr-parent'];
541                 }
542
543                 $owner = User::getOwnerDataById($item['uid']);
544
545                 if (!$object_mode) {
546                         return LDSignature::sign($data, $owner);
547                 } else {
548                         return $data;
549                 }
550         }
551
552         /**
553          * @brief Creates an object array for a given item id
554          *
555          * @param integer $item_id
556          *
557          * @return object array
558          */
559         public static function createObjectFromItemID($item_id)
560         {
561                 $item = Item::selectFirst([], ['id' => $item_id, 'parent-network' => Protocol::NATIVE_SUPPORT]);
562
563                 if (!DBA::isResult($item)) {
564                         return false;
565                 }
566
567                 $data = ['@context' => ActivityPub::CONTEXT];
568                 $data = array_merge($data, self::createNote($item));
569
570                 return $data;
571         }
572
573         /**
574          * @brief Returns a tag array for a given item array
575          *
576          * @param array $item
577          *
578          * @return array of tags
579          */
580         private static function createTagList($item)
581         {
582                 $tags = [];
583
584                 $terms = Term::tagArrayFromItemId($item['id']);
585                 foreach ($terms as $term) {
586                         if ($term['type'] == TERM_HASHTAG) {
587                                 $tags[] = ['type' => 'Hashtag', 'href' => $term['url'], 'name' => '#' . $term['term']];
588                         } elseif ($term['type'] == TERM_MENTION) {
589                                 $contact = Contact::getDetailsByURL($term['url']);
590                                 if (!empty($contact['addr'])) {
591                                         $mention = '@' . $contact['addr'];
592                                 } else {
593                                         $mention = '@' . $term['url'];
594                                 }
595
596                                 $tags[] = ['type' => 'Mention', 'href' => $term['url'], 'name' => $mention];
597                         }
598                 }
599                 return $tags;
600         }
601
602         /**
603          * @brief Adds attachment data to the JSON document
604          *
605          * @param array $item Data of the item that is to be posted
606          * @return attachment array
607          */
608
609         private static function createAttachmentList($item)
610         {
611                 $attachments = [];
612
613                 $siteinfo = BBCode::getAttachedData($item['body']);
614
615                 switch ($siteinfo['type']) {
616                         case 'photo':
617                                 if (!empty($siteinfo['image'])) {
618                                         $imgdata = Image::getInfoFromURL($siteinfo['image']);
619                                         if ($imgdata) {
620                                                 $attachments[] = ['type' => 'Document',
621                                                                 'mediaType' => $imgdata['mime'],
622                                                                 'url' => $siteinfo['image'],
623                                                                 'name' => null];
624                                         }
625                                 }
626                                 break;
627                         case 'video':
628                                 $attachments[] = ['type' => 'Document',
629                                                 'mediaType' => 'text/html; charset=UTF-8',
630                                                 'url' => $siteinfo['url'],
631                                                 'name' => defaults($siteinfo, 'title', $siteinfo['url'])];
632                                 break;
633                         default:
634                                 break;
635                 }
636
637                 if (!Config::get('system', 'ostatus_not_attach_preview') && ($siteinfo['type'] != 'photo') && isset($siteinfo['image'])) {
638                         $imgdata = Image::getInfoFromURL($siteinfo['image']);
639                         if ($imgdata) {
640                                 $attachments[] = ['type' => 'Document',
641                                                 'mediaType' => $imgdata['mime'],
642                                                 'url' => $siteinfo['image'],
643                                                 'name' => null];
644                         }
645                 }
646
647                 $arr = explode('[/attach],', $item['attach']);
648                 if (count($arr)) {
649                         foreach ($arr as $r) {
650                                 $matches = false;
651                                 $cnt = preg_match('|\[attach\]href=\"(.*?)\" length=\"(.*?)\" type=\"(.*?)\" title=\"(.*?)\"|', $r, $matches);
652                                 if ($cnt) {
653                                         $attributes = ['type' => 'Document',
654                                                         'mediaType' => $matches[3],
655                                                         'url' => $matches[1],
656                                                         'name' => null];
657
658                                         if (trim($matches[4]) != '') {
659                                                 $attributes['name'] = trim($matches[4]);
660                                         }
661
662                                         $attachments[] = $attributes;
663                                 }
664                         }
665                 }
666
667                 return $attachments;
668         }
669
670         /**
671          * @brief Fetches the "context" value for a givem item array from the "conversation" table
672          *
673          * @param array $item
674          *
675          * @return string with context url
676          */
677         private static function fetchContextURLForItem($item)
678         {
679                 $conversation = DBA::selectFirst('conversation', ['conversation-href', 'conversation-uri'], ['item-uri' => $item['parent-uri']]);
680                 if (DBA::isResult($conversation) && !empty($conversation['conversation-href'])) {
681                         $context_uri = $conversation['conversation-href'];
682                 } elseif (DBA::isResult($conversation) && !empty($conversation['conversation-uri'])) {
683                         $context_uri = $conversation['conversation-uri'];
684                 } else {
685                         $context_uri = str_replace('/objects/', '/context/', $item['parent-uri']);
686                 }
687                 return $context_uri;
688         }
689
690         private static function fetchSensitive($item_id)
691         {
692                 $condition = ['otype' => TERM_OBJ_POST, 'oid' => $item_id, 'type' => TERM_HASHTAG, 'term' => 'nsfw'];
693                 return DBA::exists('term', $condition);
694         }
695
696         /**
697          * @brief Creates a note/article object array
698          *
699          * @param array $item
700          *
701          * @return object array
702          */
703         private static function createNote($item)
704         {
705                 if (!empty($item['title'])) {
706                         $type = 'Article';
707                 } else {
708                         $type = 'Note';
709                 }
710
711                 if ($item['deleted']) {
712                         $type = 'Tombstone';
713                 }
714
715                 $data = [];
716                 $data['id'] = $item['uri'];
717                 $data['type'] = $type;
718
719                 if ($item['deleted']) {
720                         return $data;
721                 }
722
723                 $data['summary'] = null; // Ignore by now
724
725                 if ($item['uri'] != $item['thr-parent']) {
726                         $data['inReplyTo'] = $item['thr-parent'];
727                 } else {
728                         $data['inReplyTo'] = null;
729                 }
730
731                 $data['diaspora:guid'] = $item['guid'];
732                 $data['published'] = DateTimeFormat::utc($item["created"]."+00:00", DateTimeFormat::ATOM);
733
734                 if ($item["created"] != $item["edited"]) {
735                         $data['updated'] = DateTimeFormat::utc($item["edited"]."+00:00", DateTimeFormat::ATOM);
736                 }
737
738                 $data['url'] = $item['plink'];
739                 $data['attributedTo'] = $item['author-link'];
740                 $data['actor'] = $item['author-link'];
741                 $data['sensitive'] = self::fetchSensitive($item['id']);
742                 $data['context'] = self::fetchContextURLForItem($item);
743
744                 if (!empty($item['title'])) {
745                         $data['name'] = BBCode::convert($item['title'], false, 7);
746                 }
747
748                 $data['content'] = BBCode::convert($item['body'], false, 7);
749                 $data['source'] = ['content' => $item['body'], 'mediaType' => "text/bbcode"];
750
751                 if (!empty($item['signed_text']) && ($item['uri'] != $item['thr-parent'])) {
752                         $data['diaspora:comment'] = $item['signed_text'];
753                 }
754
755                 $data['attachment'] = self::createAttachmentList($item);
756                 $data['tag'] = self::createTagList($item);
757                 $data = array_merge($data, self::createPermissionBlockForItem($item));
758
759                 return $data;
760         }
761
762         /**
763          * @brief Transmits a profile deletion to a given inbox
764          *
765          * @param integer $uid User ID
766          * @param string $inbox Target inbox
767          */
768         public static function sendProfileDeletion($uid, $inbox)
769         {
770                 $owner = User::getOwnerDataById($uid);
771                 $profile = APContact::getByURL($owner['url']);
772
773                 $data = ['@context' => 'https://www.w3.org/ns/activitystreams',
774                         'id' => System::baseUrl() . '/activity/' . System::createGUID(),
775                         'type' => 'Delete',
776                         'actor' => $owner['url'],
777                         'object' => $owner['url'],
778                         'published' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
779                         'to' => [ActivityPub::PUBLIC_COLLECTION],
780                         'cc' => []];
781
782                 $signed = LDSignature::sign($data, $owner);
783
784                 logger('Deliver profile deletion for user ' . $uid . ' to ' . $inbox .' via ActivityPub', LOGGER_DEBUG);
785                 HTTPSignature::transmit($signed, $inbox, $uid);
786         }
787
788         /**
789          * @brief Transmits a profile change to a given inbox
790          *
791          * @param integer $uid User ID
792          * @param string $inbox Target inbox
793          */
794         public static function sendProfileUpdate($uid, $inbox)
795         {
796                 $owner = User::getOwnerDataById($uid);
797                 $profile = APContact::getByURL($owner['url']);
798
799                 $data = ['@context' => 'https://www.w3.org/ns/activitystreams',
800                         'id' => System::baseUrl() . '/activity/' . System::createGUID(),
801                         'type' => 'Update',
802                         'actor' => $owner['url'],
803                         'object' => self::getProfile($uid),
804                         'published' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
805                         'to' => [$profile['followers']],
806                         'cc' => []];
807
808                 $signed = LDSignature::sign($data, $owner);
809
810                 logger('Deliver profile update for user ' . $uid . ' to ' . $inbox .' via ActivityPub', LOGGER_DEBUG);
811                 HTTPSignature::transmit($signed, $inbox, $uid);
812         }
813
814         /**
815          * @brief Transmits a given activity to a target
816          *
817          * @param array $activity
818          * @param string $target Target profile
819          * @param integer $uid User ID
820          */
821         public static function sendActivity($activity, $target, $uid)
822         {
823                 $profile = APContact::getByURL($target);
824
825                 $owner = User::getOwnerDataById($uid);
826
827                 $data = ['@context' => 'https://www.w3.org/ns/activitystreams',
828                         'id' => System::baseUrl() . '/activity/' . System::createGUID(),
829                         'type' => $activity,
830                         'actor' => $owner['url'],
831                         'object' => $profile['url'],
832                         'to' => $profile['url']];
833
834                 logger('Sending activity ' . $activity . ' to ' . $target . ' for user ' . $uid, LOGGER_DEBUG);
835
836                 $signed = LDSignature::sign($data, $owner);
837                 HTTPSignature::transmit($signed, $profile['inbox'], $uid);
838         }
839
840         /**
841          * @brief Transmit a message that the contact request had been accepted
842          *
843          * @param string $target Target profile
844          * @param $id
845          * @param integer $uid User ID
846          */
847         public static function sendContactAccept($target, $id, $uid)
848         {
849                 $profile = APContact::getByURL($target);
850
851                 $owner = User::getOwnerDataById($uid);
852                 $data = ['@context' => 'https://www.w3.org/ns/activitystreams',
853                         'id' => System::baseUrl() . '/activity/' . System::createGUID(),
854                         'type' => 'Accept',
855                         'actor' => $owner['url'],
856                         'object' => ['id' => $id, 'type' => 'Follow',
857                                 'actor' => $profile['url'],
858                                 'object' => $owner['url']],
859                         'to' => $profile['url']];
860
861                 logger('Sending accept to ' . $target . ' for user ' . $uid . ' with id ' . $id, LOGGER_DEBUG);
862
863                 $signed = LDSignature::sign($data, $owner);
864                 HTTPSignature::transmit($signed, $profile['inbox'], $uid);
865         }
866
867         /**
868          * @brief 
869          *
870          * @param string $target Target profile
871          * @param $id
872          * @param integer $uid User ID
873          */
874         public static function sendContactReject($target, $id, $uid)
875         {
876                 $profile = APContact::getByURL($target);
877
878                 $owner = User::getOwnerDataById($uid);
879                 $data = ['@context' => 'https://www.w3.org/ns/activitystreams',
880                         'id' => System::baseUrl() . '/activity/' . System::createGUID(),
881                         'type' => 'Reject',
882                         'actor' => $owner['url'],
883                         'object' => ['id' => $id, 'type' => 'Follow',
884                                 'actor' => $profile['url'],
885                                 'object' => $owner['url']],
886                         'to' => $profile['url']];
887
888                 logger('Sending reject to ' . $target . ' for user ' . $uid . ' with id ' . $id, LOGGER_DEBUG);
889
890                 $signed = LDSignature::sign($data, $owner);
891                 HTTPSignature::transmit($signed, $profile['inbox'], $uid);
892         }
893
894         /**
895          * @brief 
896          *
897          * @param string $target Target profile
898          * @param integer $uid User ID
899          */
900         public static function sendContactUndo($target, $uid)
901         {
902                 $profile = APContact::getByURL($target);
903
904                 $id = System::baseUrl() . '/activity/' . System::createGUID();
905
906                 $owner = User::getOwnerDataById($uid);
907                 $data = ['@context' => 'https://www.w3.org/ns/activitystreams',
908                         'id' => $id,
909                         'type' => 'Undo',
910                         'actor' => $owner['url'],
911                         'object' => ['id' => $id, 'type' => 'Follow',
912                                 'actor' => $owner['url'],
913                                 'object' => $profile['url']],
914                         'to' => $profile['url']];
915
916                 logger('Sending undo to ' . $target . ' for user ' . $uid . ' with id ' . $id, LOGGER_DEBUG);
917
918                 $signed = LDSignature::sign($data, $owner);
919                 HTTPSignature::transmit($signed, $profile['inbox'], $uid);
920         }
921 }