]> git.mxchange.org Git - friendica.git/blob - src/Protocol/ActivityPub.php
Some more documentation
[friendica.git] / src / Protocol / ActivityPub.php
1 <?php
2 /**
3  * @file src/Protocol/ActivityPub.php
4  */
5 namespace Friendica\Protocol;
6
7 use Friendica\Database\DBA;
8 use Friendica\Core\System;
9 use Friendica\BaseObject;
10 use Friendica\Util\Network;
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\Profile;
18 use Friendica\Model\Term;
19 use Friendica\Model\User;
20 use Friendica\Util\DateTimeFormat;
21 use Friendica\Util\Crypto;
22 use Friendica\Content\Text\BBCode;
23 use Friendica\Content\Text\HTML;
24 use Friendica\Util\JsonLD;
25 use Friendica\Util\LDSignature;
26 use Friendica\Core\Config;
27
28 /**
29  * @brief ActivityPub Protocol class
30  * The ActivityPub Protocol is a message exchange protocol defined by the W3C.
31  * https://www.w3.org/TR/activitypub/
32  * https://www.w3.org/TR/activitystreams-core/
33  * https://www.w3.org/TR/activitystreams-vocabulary/
34  *
35  * https://blog.joinmastodon.org/2018/06/how-to-implement-a-basic-activitypub-server/
36  * https://blog.joinmastodon.org/2018/07/how-to-make-friends-and-verify-requests/
37  *
38  * Digest: https://tools.ietf.org/html/rfc5843
39  * https://tools.ietf.org/html/draft-cavage-http-signatures-10#ref-15
40  *
41  * Mastodon implementation of supported activities:
42  * https://github.com/tootsuite/mastodon/blob/master/app/lib/activitypub/activity.rb#L26
43  *
44  * To-do:
45  *
46  * Receiver:
47  * - Update Note
48  * - Delete Note
49  * - Delete Person
50  * - Undo Announce
51  * - Reject Follow
52  * - Undo Accept
53  * - Undo Follow
54  * - Add
55  * - Create Image
56  * - Create Video
57  * - Event
58  * - Remove
59  * - Block
60  * - Flag
61  *
62  * Transmitter:
63  * - Announce
64  * - Undo Announce
65  * - Update Person
66  * - Reject Follow
67  * - Event
68  *
69  * General:
70  * - Attachments
71  * - nsfw (sensitive)
72  * - Queueing unsucessful deliveries
73  * - Polling the outboxes for missing content?
74  * - Possibly using the LD-JSON parser
75  */
76 class ActivityPub
77 {
78         const PUBLIC = 'https://www.w3.org/ns/activitystreams#Public';
79         const CONTEXT = ['https://www.w3.org/ns/activitystreams', 'https://w3id.org/security/v1',
80                 ['vcard' => 'http://www.w3.org/2006/vcard/ns#',
81                 'diaspora' => 'https://diasporafoundation.org#',
82                 'manuallyApprovesFollowers' => 'as:manuallyApprovesFollowers',
83                 'sensitive' => 'as:sensitive', 'Hashtag' => 'as:Hashtag']];
84
85         /**
86          * @brief Checks if the web request is done for the AP protocol
87          *
88          * @return is it AP?
89          */
90         public static function isRequest()
91         {
92                 return stristr(defaults($_SERVER, 'HTTP_ACCEPT', ''), 'application/activity+json') ||
93                         stristr(defaults($_SERVER, 'HTTP_ACCEPT', ''), 'application/ld+json');
94         }
95
96         /**
97          * @brief collects the lost of followers of the given owner
98          *
99          * @param array $owner Owner array
100          * @param integer $page Page number
101          *
102          * @return array of owners
103          */
104         public static function getFollowers($owner, $page = null)
105         {
106                 $condition = ['rel' => [Contact::FOLLOWER, Contact::FRIEND], 'network' => Protocol::NATIVE_SUPPORT, 'uid' => $owner['uid'],
107                         'self' => false, 'hidden' => false, 'archive' => false, 'pending' => false];
108                 $count = DBA::count('contact', $condition);
109
110                 $data = ['@context' => self::CONTEXT];
111                 $data['id'] = System::baseUrl() . '/followers/' . $owner['nickname'];
112                 $data['type'] = 'OrderedCollection';
113                 $data['totalItems'] = $count;
114
115                 // When we hide our friends we will only show the pure number but don't allow more.
116                 $profile = Profile::getProfileForUser($owner['uid']);
117                 if (!empty($profile['hide-friends'])) {
118                         return $data;
119                 }
120
121                 if (empty($page)) {
122                         $data['first'] = System::baseUrl() . '/followers/' . $owner['nickname'] . '?page=1';
123                 } else {
124                         $list = [];
125
126                         $contacts = DBA::select('contact', ['url'], $condition, ['limit' => [($page - 1) * 100, 100]]);
127                         while ($contact = DBA::fetch($contacts)) {
128                                 $list[] = $contact['url'];
129                         }
130
131                         if (!empty($list)) {
132                                 $data['next'] = System::baseUrl() . '/followers/' . $owner['nickname'] . '?page=' . ($page + 1);
133                         }
134
135                         $data['partOf'] = System::baseUrl() . '/followers/' . $owner['nickname'];
136
137                         $data['orderedItems'] = $list;
138                 }
139
140                 return $data;
141         }
142
143         /**
144          * @brief Create list of following contacts
145          *
146          * @param array $owner Owner array
147          * @param integer $page Page numbe
148          *
149          * @return array of following contacts
150          */
151         public static function getFollowing($owner, $page = null)
152         {
153                 $condition = ['rel' => [Contact::SHARING, Contact::FRIEND], 'network' => Protocol::NATIVE_SUPPORT, 'uid' => $owner['uid'],
154                         'self' => false, 'hidden' => false, 'archive' => false, 'pending' => false];
155                 $count = DBA::count('contact', $condition);
156
157                 $data = ['@context' => self::CONTEXT];
158                 $data['id'] = System::baseUrl() . '/following/' . $owner['nickname'];
159                 $data['type'] = 'OrderedCollection';
160                 $data['totalItems'] = $count;
161
162                 // When we hide our friends we will only show the pure number but don't allow more.
163                 $profile = Profile::getProfileForUser($owner['uid']);
164                 if (!empty($profile['hide-friends'])) {
165                         return $data;
166                 }
167
168                 if (empty($page)) {
169                         $data['first'] = System::baseUrl() . '/following/' . $owner['nickname'] . '?page=1';
170                 } else {
171                         $list = [];
172
173                         $contacts = DBA::select('contact', ['url'], $condition, ['limit' => [($page - 1) * 100, 100]]);
174                         while ($contact = DBA::fetch($contacts)) {
175                                 $list[] = $contact['url'];
176                         }
177
178                         if (!empty($list)) {
179                                 $data['next'] = System::baseUrl() . '/following/' . $owner['nickname'] . '?page=' . ($page + 1);
180                         }
181
182                         $data['partOf'] = System::baseUrl() . '/following/' . $owner['nickname'];
183
184                         $data['orderedItems'] = $list;
185                 }
186
187                 return $data;
188         }
189
190         /**
191          * @brief Public posts for the given owner
192          *
193          * @param array $owner Owner array
194          * @param integer $page Page numbe
195          *
196          * @return array of posts
197          */
198         public static function getOutbox($owner, $page = null)
199         {
200                 $public_contact = Contact::getIdForURL($owner['url'], 0, true);
201
202                 $condition = ['uid' => $owner['uid'], 'contact-id' => $owner['id'], 'author-id' => $public_contact,
203                         'wall' => true, 'private' => false, 'gravity' => [GRAVITY_PARENT, GRAVITY_COMMENT],
204                         'deleted' => false, 'visible' => true];
205                 $count = DBA::count('item', $condition);
206
207                 $data = ['@context' => self::CONTEXT];
208                 $data['id'] = System::baseUrl() . '/outbox/' . $owner['nickname'];
209                 $data['type'] = 'OrderedCollection';
210                 $data['totalItems'] = $count;
211
212                 if (empty($page)) {
213                         $data['first'] = System::baseUrl() . '/outbox/' . $owner['nickname'] . '?page=1';
214                 } else {
215                         $list = [];
216
217                         $condition['parent-network'] = Protocol::NATIVE_SUPPORT;
218
219                         $items = Item::select(['id'], $condition, ['limit' => [($page - 1) * 20, 20], 'order' => ['created' => true]]);
220                         while ($item = Item::fetch($items)) {
221                                 $object = self::createObjectFromItemID($item['id']);
222                                 unset($object['@context']);
223                                 $list[] = $object;
224                         }
225
226                         if (!empty($list)) {
227                                 $data['next'] = System::baseUrl() . '/outbox/' . $owner['nickname'] . '?page=' . ($page + 1);
228                         }
229
230                         $data['partOf'] = System::baseUrl() . '/outbox/' . $owner['nickname'];
231
232                         $data['orderedItems'] = $list;
233                 }
234
235                 return $data;
236         }
237
238         /**
239          * Return the ActivityPub profile of the given user
240          *
241          * @param integer $uid User ID
242          * @return profile array
243          */
244         public static function profile($uid)
245         {
246                 $accounttype = ['Person', 'Organization', 'Service', 'Group', 'Application'];
247                 $condition = ['uid' => $uid, 'blocked' => false, 'account_expired' => false,
248                         'account_removed' => false, 'verified' => true];
249                 $fields = ['guid', 'nickname', 'pubkey', 'account-type', 'page-flags'];
250                 $user = DBA::selectFirst('user', $fields, $condition);
251                 if (!DBA::isResult($user)) {
252                         return [];
253                 }
254
255                 $fields = ['locality', 'region', 'country-name'];
256                 $profile = DBA::selectFirst('profile', $fields, ['uid' => $uid, 'is-default' => true]);
257                 if (!DBA::isResult($profile)) {
258                         return [];
259                 }
260
261                 $fields = ['name', 'url', 'location', 'about', 'avatar'];
262                 $contact = DBA::selectFirst('contact', $fields, ['uid' => $uid, 'self' => true]);
263                 if (!DBA::isResult($contact)) {
264                         return [];
265                 }
266
267                 $data = ['@context' => self::CONTEXT];
268                 $data['id'] = $contact['url'];
269                 $data['diaspora:guid'] = $user['guid'];
270                 $data['type'] = $accounttype[$user['account-type']];
271                 $data['following'] = System::baseUrl() . '/following/' . $user['nickname'];
272                 $data['followers'] = System::baseUrl() . '/followers/' . $user['nickname'];
273                 $data['inbox'] = System::baseUrl() . '/inbox/' . $user['nickname'];
274                 $data['outbox'] = System::baseUrl() . '/outbox/' . $user['nickname'];
275                 $data['preferredUsername'] = $user['nickname'];
276                 $data['name'] = $contact['name'];
277                 $data['vcard:hasAddress'] = ['@type' => 'vcard:Home', 'vcard:country-name' => $profile['country-name'],
278                         'vcard:region' => $profile['region'], 'vcard:locality' => $profile['locality']];
279                 $data['summary'] = $contact['about'];
280                 $data['url'] = $contact['url'];
281                 $data['manuallyApprovesFollowers'] = in_array($user['page-flags'], [Contact::PAGE_NORMAL, Contact::PAGE_PRVGROUP]);
282                 $data['publicKey'] = ['id' => $contact['url'] . '#main-key',
283                         'owner' => $contact['url'],
284                         'publicKeyPem' => $user['pubkey']];
285                 $data['endpoints'] = ['sharedInbox' => System::baseUrl() . '/inbox'];
286                 $data['icon'] = ['type' => 'Image',
287                         'url' => $contact['avatar']];
288
289                 // tags: https://kitty.town/@inmysocks/100656097926961126.json
290                 return $data;
291         }
292
293         /**
294          * @brief Returns an array with permissions of a given item array
295          *
296          * @param array $item
297          *
298          * @return array with permissions
299          */
300         private static function fetchPermissionBlockFromConversation($item)
301         {
302                 if (empty($item['thr-parent'])) {
303                         return [];
304                 }
305
306                 $condition = ['item-uri' => $item['thr-parent'], 'protocol' => Conversation::PARCEL_ACTIVITYPUB];
307                 $conversation = DBA::selectFirst('conversation', ['source'], $condition);
308                 if (!DBA::isResult($conversation)) {
309                         return [];
310                 }
311
312                 $activity = json_decode($conversation['source'], true);
313
314                 $actor = JsonLD::fetchElement($activity, 'actor', 'id');
315                 $profile = APContact::getProfileByURL($actor);
316
317                 $item_profile = APContact::getProfileByURL($item['author-link']);
318                 $exclude[] = $item['author-link'];
319
320                 if ($item['gravity'] == GRAVITY_PARENT) {
321                         $exclude[] = $item['owner-link'];
322                 }
323
324                 $permissions['to'][] = $actor;
325
326                 $elements = ['to', 'cc', 'bto', 'bcc'];
327                 foreach ($elements as $element) {
328                         if (empty($activity[$element])) {
329                                 continue;
330                         }
331                         if (is_string($activity[$element])) {
332                                 $activity[$element] = [$activity[$element]];
333                         }
334
335                         foreach ($activity[$element] as $receiver) {
336                                 if ($receiver == $profile['followers'] && !empty($item_profile['followers'])) {
337                                         $receiver = $item_profile['followers'];
338                                 }
339                                 if (!in_array($receiver, $exclude)) {
340                                         $permissions[$element][] = $receiver;
341                                 }
342                         }
343                 }
344                 return $permissions;
345         }
346
347         /**
348          * @brief Creates an array of permissions from an item thread
349          *
350          * @param array $item
351          *
352          * @return permission array
353          */
354         public static function createPermissionBlockForItem($item)
355         {
356                 $data = ['to' => [], 'cc' => []];
357
358                 $data = array_merge($data, self::fetchPermissionBlockFromConversation($item));
359
360                 $actor_profile = APContact::getProfileByURL($item['author-link']);
361
362                 $terms = Term::tagArrayFromItemId($item['id']);
363
364                 $contacts[$item['author-link']] = $item['author-link'];
365
366                 if (!$item['private']) {
367                         $data['to'][] = self::PUBLIC;
368                         if (!empty($actor_profile['followers'])) {
369                                 $data['cc'][] = $actor_profile['followers'];
370                         }
371
372                         foreach ($terms as $term) {
373                                 if ($term['type'] != TERM_MENTION) {
374                                         continue;
375                                 }
376                                 $profile = APContact::getProfileByURL($term['url'], false);
377                                 if (!empty($profile) && empty($contacts[$profile['url']])) {
378                                         $data['cc'][] = $profile['url'];
379                                         $contacts[$profile['url']] = $profile['url'];
380                                 }
381                         }
382                 } else {
383                         $receiver_list = Item::enumeratePermissions($item);
384
385                         $mentioned = [];
386
387                         foreach ($terms as $term) {
388                                 if ($term['type'] != TERM_MENTION) {
389                                         continue;
390                                 }
391                                 $cid = Contact::getIdForURL($term['url'], $item['uid']);
392                                 if (!empty($cid) && in_array($cid, $receiver_list)) {
393                                         $contact = DBA::selectFirst('contact', ['url'], ['id' => $cid, 'network' => Protocol::ACTIVITYPUB]);
394                                         $data['to'][] = $contact['url'];
395                                         $contacts[$contact['url']] = $contact['url'];
396                                 }
397                         }
398
399                         foreach ($receiver_list as $receiver) {
400                                 $contact = DBA::selectFirst('contact', ['url'], ['id' => $receiver, 'network' => Protocol::ACTIVITYPUB]);
401                                 if (empty($contacts[$contact['url']])) {
402                                         $data['cc'][] = $contact['url'];
403                                         $contacts[$contact['url']] = $contact['url'];
404                                 }
405                         }
406                 }
407
408                 $parents = Item::select(['id', 'author-link', 'owner-link', 'gravity'], ['parent' => $item['parent']]);
409                 while ($parent = Item::fetch($parents)) {
410                         // Don't include data from future posts
411                         if ($parent['id'] >= $item['id']) {
412                                 continue;
413                         }
414
415                         $profile = APContact::getProfileByURL($parent['author-link'], false);
416                         if (!empty($profile) && empty($contacts[$profile['url']])) {
417                                 $data['cc'][] = $profile['url'];
418                                 $contacts[$profile['url']] = $profile['url'];
419                         }
420
421                         if ($item['gravity'] != GRAVITY_PARENT) {
422                                 continue;
423                         }
424
425                         $profile = APContact::getProfileByURL($parent['owner-link'], false);
426                         if (!empty($profile) && empty($contacts[$profile['url']])) {
427                                 $data['cc'][] = $profile['url'];
428                                 $contacts[$profile['url']] = $profile['url'];
429                         }
430                 }
431                 DBA::close($parents);
432
433                 if (empty($data['to'])) {
434                         $data['to'] = $data['cc'];
435                         $data['cc'] = [];
436                 }
437
438                 return $data;
439         }
440
441         /**
442          * @brief Fetches an array of inboxes for the given item and user
443          *
444          * @param array $item
445          * @param integer $uid User ID
446          *
447          * @return array with inboxes
448          */
449         public static function fetchTargetInboxes($item, $uid)
450         {
451                 $permissions = self::createPermissionBlockForItem($item);
452                 if (empty($permissions)) {
453                         return [];
454                 }
455
456                 $inboxes = [];
457
458                 if ($item['gravity'] == GRAVITY_ACTIVITY) {
459                         $item_profile = APContact::getProfileByURL($item['author-link']);
460                 } else {
461                         $item_profile = APContact::getProfileByURL($item['owner-link']);
462                 }
463
464                 $elements = ['to', 'cc', 'bto', 'bcc'];
465                 foreach ($elements as $element) {
466                         if (empty($permissions[$element])) {
467                                 continue;
468                         }
469
470                         foreach ($permissions[$element] as $receiver) {
471                                 if ($receiver == $item_profile['followers']) {
472                                         $contacts = DBA::select('contact', ['notify', 'batch'], ['uid' => $uid,
473                                                 'rel' => [Contact::FOLLOWER, Contact::FRIEND], 'network' => Protocol::ACTIVITYPUB]);
474                                         while ($contact = DBA::fetch($contacts)) {
475                                                 $contact = defaults($contact, 'batch', $contact['notify']);
476                                                 $inboxes[$contact] = $contact;
477                                         }
478                                         DBA::close($contacts);
479                                 } else {
480                                         $profile = APContact::getProfileByURL($receiver);
481                                         if (!empty($profile)) {
482                                                 $target = defaults($profile, 'sharedinbox', $profile['inbox']);
483                                                 $inboxes[$target] = $target;
484                                         }
485                                 }
486                         }
487                 }
488
489                 return $inboxes;
490         }
491
492         /**
493          * @brief Returns the activity type of a given item
494          *
495          * @param array $item
496          *
497          * @return activity type
498          */
499         public static function getTypeOfItem($item)
500         {
501                 if ($item['verb'] == ACTIVITY_POST) {
502                         if ($item['created'] == $item['edited']) {
503                                 $type = 'Create';
504                         } else {
505                                 $type = 'Update';
506                         }
507                 } elseif ($item['verb'] == ACTIVITY_LIKE) {
508                         $type = 'Like';
509                 } elseif ($item['verb'] == ACTIVITY_DISLIKE) {
510                         $type = 'Dislike';
511                 } elseif ($item['verb'] == ACTIVITY_ATTEND) {
512                         $type = 'Accept';
513                 } elseif ($item['verb'] == ACTIVITY_ATTENDNO) {
514                         $type = 'Reject';
515                 } elseif ($item['verb'] == ACTIVITY_ATTENDMAYBE) {
516                         $type = 'TentativeAccept';
517                 } else {
518                         $type = '';
519                 }
520
521                 return $type;
522         }
523
524         /**
525          * @brief Creates an activity array for a given item id
526          *
527          * @param integer $item_id
528          * @param boolean $object_mode Is the activity item is used inside another object?
529          *
530          * @return array of activity
531          */
532         public static function createActivityFromItem($item_id, $object_mode = false)
533         {
534                 $item = Item::selectFirst([], ['id' => $item_id, 'parent-network' => Protocol::NATIVE_SUPPORT]);
535
536                 if (!DBA::isResult($item)) {
537                         return false;
538                 }
539
540                 $condition = ['item-uri' => $item['uri'], 'protocol' => Conversation::PARCEL_ACTIVITYPUB];
541                 $conversation = DBA::selectFirst('conversation', ['source'], $condition);
542                 if (DBA::isResult($conversation)) {
543                         $data = json_decode($conversation['source']);
544                         if (!empty($data)) {
545                                 return $data;
546                         }
547                 }
548
549                 $type = self::getTypeOfItem($item);
550
551                 if (!$object_mode) {
552                         $data = ['@context' => self::CONTEXT];
553
554                         if ($item['deleted'] && ($item['gravity'] == GRAVITY_ACTIVITY)) {
555                                 $type = 'Undo';
556                         } elseif ($item['deleted']) {
557                                 $type = 'Delete';
558                         }
559                 } else {
560                         $data = [];
561                 }
562
563                 $data['id'] = $item['uri'] . '#' . $type;
564                 $data['type'] = $type;
565                 $data['actor'] = $item['author-link'];
566
567                 $data['published'] = DateTimeFormat::utc($item["created"]."+00:00", DateTimeFormat::ATOM);
568
569                 if ($item["created"] != $item["edited"]) {
570                         $data['updated'] = DateTimeFormat::utc($item["edited"]."+00:00", DateTimeFormat::ATOM);
571                 }
572
573                 $data['context'] = self::fetchContextURLForItem($item);
574
575                 $data = array_merge($data, ActivityPub::createPermissionBlockForItem($item));
576
577                 if (in_array($data['type'], ['Create', 'Update', 'Announce', 'Delete'])) {
578                         $data['object'] = self::CreateNote($item);
579                 } elseif ($data['type'] == 'Undo') {
580                         $data['object'] = self::createActivityFromItem($item_id, true);
581                 } else {
582                         $data['object'] = $item['thr-parent'];
583                 }
584
585                 $owner = User::getOwnerDataById($item['uid']);
586
587                 if (!$object_mode) {
588                         return LDSignature::sign($data, $owner);
589                 } else {
590                         return $data;
591                 }
592         }
593
594         /**
595          * @brief Creates an object array for a given item id
596          *
597          * @param integer $item_id
598          *
599          * @return object array
600          */
601         public static function createObjectFromItemID($item_id)
602         {
603                 $item = Item::selectFirst([], ['id' => $item_id, 'parent-network' => Protocol::NATIVE_SUPPORT]);
604
605                 if (!DBA::isResult($item)) {
606                         return false;
607                 }
608
609                 $data = ['@context' => self::CONTEXT];
610                 $data = array_merge($data, self::CreateNote($item));
611
612                 return $data;
613         }
614
615         /**
616          * @brief Returns a tag array for a given item array
617          *
618          * @param array $item
619          *
620          * @return array of tags
621          */
622         private static function createTagList($item)
623         {
624                 $tags = [];
625
626                 $terms = Term::tagArrayFromItemId($item['id']);
627                 foreach ($terms as $term) {
628                         if ($term['type'] == TERM_MENTION) {
629                                 $contact = Contact::getDetailsByURL($term['url']);
630                                 if (!empty($contact['addr'])) {
631                                         $mention = '@' . $contact['addr'];
632                                 } else {
633                                         $mention = '@' . $term['url'];
634                                 }
635
636                                 $tags[] = ['type' => 'Mention', 'href' => $term['url'], 'name' => $mention];
637                         }
638                 }
639                 return $tags;
640         }
641
642         /**
643          * @brief Fetches the "context" value for a givem item array from the "conversation" table
644          *
645          * @param array $item
646          *
647          * @return string with context url
648          */
649         private static function fetchContextURLForItem($item)
650         {
651                 $conversation = DBA::selectFirst('conversation', ['conversation-href', 'conversation-uri'], ['item-uri' => $item['parent-uri']]);
652                 if (DBA::isResult($conversation) && !empty($conversation['conversation-href'])) {
653                         $context_uri = $conversation['conversation-href'];
654                 } elseif (DBA::isResult($conversation) && !empty($conversation['conversation-uri'])) {
655                         $context_uri = $conversation['conversation-uri'];
656                 } else {
657                         $context_uri = str_replace('/object/', '/context/', $item['parent-uri']);
658                 }
659                 return $context_uri;
660         }
661
662         /**
663          * @brief Creates a note/article object array
664          *
665          * @param array $item
666          *
667          * @return object array
668          */
669         private static function CreateNote($item)
670         {
671                 if (!empty($item['title'])) {
672                         $type = 'Article';
673                 } else {
674                         $type = 'Note';
675                 }
676
677                 if ($item['deleted']) {
678                         $type = 'Tombstone';
679                 }
680
681                 $data = [];
682                 $data['id'] = $item['uri'];
683                 $data['type'] = $type;
684
685                 if ($item['deleted']) {
686                         return $data;
687                 }
688
689                 $data['summary'] = null; // Ignore by now
690
691                 if ($item['uri'] != $item['thr-parent']) {
692                         $data['inReplyTo'] = $item['thr-parent'];
693                 } else {
694                         $data['inReplyTo'] = null;
695                 }
696
697                 $data['diaspora:guid'] = $item['guid'];
698                 $data['published'] = DateTimeFormat::utc($item["created"]."+00:00", DateTimeFormat::ATOM);
699
700                 if ($item["created"] != $item["edited"]) {
701                         $data['updated'] = DateTimeFormat::utc($item["edited"]."+00:00", DateTimeFormat::ATOM);
702                 }
703
704                 $data['url'] = $item['plink'];
705                 $data['attributedTo'] = $item['author-link'];
706                 $data['actor'] = $item['author-link'];
707                 $data['sensitive'] = false; // - Query NSFW
708                 $data['context'] = self::fetchContextURLForItem($item);
709
710                 if (!empty($item['title'])) {
711                         $data['name'] = BBCode::convert($item['title'], false, 7);
712                 }
713
714                 $data['content'] = BBCode::convert($item['body'], false, 7);
715                 $data['source'] = ['content' => $item['body'], 'mediaType' => "text/bbcode"];
716                 $data['attachment'] = []; // @ToDo
717                 $data['tag'] = self::createTagList($item);
718                 $data = array_merge($data, ActivityPub::createPermissionBlockForItem($item));
719
720                 return $data;
721         }
722
723         /**
724          * @brief Transmits a given activity to a target
725          *
726          * @param array $activity
727          * @param string $target Target profile
728          * @param integer $uid User ID
729          */
730         public static function transmitActivity($activity, $target, $uid)
731         {
732                 $profile = APContact::getProfileByURL($target);
733
734                 $owner = User::getOwnerDataById($uid);
735
736                 $data = ['@context' => 'https://www.w3.org/ns/activitystreams',
737                         'id' => System::baseUrl() . '/activity/' . System::createGUID(),
738                         'type' => $activity,
739                         'actor' => $owner['url'],
740                         'object' => $profile['url'],
741                         'to' => $profile['url']];
742
743                 logger('Sending activity ' . $activity . ' to ' . $target . ' for user ' . $uid, LOGGER_DEBUG);
744
745                 $signed = LDSignature::sign($data, $owner);
746                 HTTPSignature::transmit($signed, $profile['inbox'], $uid);
747         }
748
749         /**
750          * @brief Transmit a message that the contact request had been accepted
751          *
752          * @param string $target Target profile
753          * @param $id
754          * @param integer $uid User ID
755          */
756         public static function transmitContactAccept($target, $id, $uid)
757         {
758                 $profile = APContact::getProfileByURL($target);
759
760                 $owner = User::getOwnerDataById($uid);
761                 $data = ['@context' => 'https://www.w3.org/ns/activitystreams',
762                         'id' => System::baseUrl() . '/activity/' . System::createGUID(),
763                         'type' => 'Accept',
764                         'actor' => $owner['url'],
765                         'object' => ['id' => $id, 'type' => 'Follow',
766                                 'actor' => $profile['url'],
767                                 'object' => $owner['url']],
768                         'to' => $profile['url']];
769
770                 logger('Sending accept to ' . $target . ' for user ' . $uid . ' with id ' . $id, LOGGER_DEBUG);
771
772                 $signed = LDSignature::sign($data, $owner);
773                 HTTPSignature::transmit($signed, $profile['inbox'], $uid);
774         }
775
776         /**
777          * @brief 
778          *
779          * @param string $target Target profile
780          * @param $id
781          * @param integer $uid User ID
782          */
783         public static function transmitContactReject($target, $id, $uid)
784         {
785                 $profile = APContact::getProfileByURL($target);
786
787                 $owner = User::getOwnerDataById($uid);
788                 $data = ['@context' => 'https://www.w3.org/ns/activitystreams',
789                         'id' => System::baseUrl() . '/activity/' . System::createGUID(),
790                         'type' => 'Reject',
791                         'actor' => $owner['url'],
792                         'object' => ['id' => $id, 'type' => 'Follow',
793                                 'actor' => $profile['url'],
794                                 'object' => $owner['url']],
795                         'to' => $profile['url']];
796
797                 logger('Sending reject to ' . $target . ' for user ' . $uid . ' with id ' . $id, LOGGER_DEBUG);
798
799                 $signed = LDSignature::sign($data, $owner);
800                 HTTPSignature::transmit($signed, $profile['inbox'], $uid);
801         }
802
803         /**
804          * @brief 
805          *
806          * @param string $target Target profile
807          * @param integer $uid User ID
808          */
809         public static function transmitContactUndo($target, $uid)
810         {
811                 $profile = APContact::getProfileByURL($target);
812
813                 $id = System::baseUrl() . '/activity/' . System::createGUID();
814
815                 $owner = User::getOwnerDataById($uid);
816                 $data = ['@context' => 'https://www.w3.org/ns/activitystreams',
817                         'id' => $id,
818                         'type' => 'Undo',
819                         'actor' => $owner['url'],
820                         'object' => ['id' => $id, 'type' => 'Follow',
821                                 'actor' => $owner['url'],
822                                 'object' => $profile['url']],
823                         'to' => $profile['url']];
824
825                 logger('Sending undo to ' . $target . ' for user ' . $uid . ' with id ' . $id, LOGGER_DEBUG);
826
827                 $signed = LDSignature::sign($data, $owner);
828                 HTTPSignature::transmit($signed, $profile['inbox'], $uid);
829         }
830
831         /**
832          * Fetches ActivityPub content from the given url
833          *
834          * @param string $url content url
835          * @return array
836          */
837         public static function fetchContent($url)
838         {
839                 $ret = Network::curl($url, false, $redirects, ['accept_content' => 'application/activity+json, application/ld+json']);
840                 if (!$ret['success'] || empty($ret['body'])) {
841                         return;
842                 }
843                 return json_decode($ret['body'], true);
844         }
845
846         /**
847          * Fetches a profile from the given url into an array that is compatible to Probe::uri
848          *
849          * @param string $url profile url
850          * @return array
851          */
852         public static function probeProfile($url)
853         {
854                 $apcontact = APContact::getProfileByURL($url, true);
855                 if (empty($apcontact)) {
856                         return false;
857                 }
858
859                 $profile = ['network' => Protocol::ACTIVITYPUB];
860                 $profile['nick'] = $apcontact['nick'];
861                 $profile['name'] = $apcontact['name'];
862                 $profile['guid'] = $apcontact['uuid'];
863                 $profile['url'] = $apcontact['url'];
864                 $profile['addr'] = $apcontact['addr'];
865                 $profile['alias'] = $apcontact['alias'];
866                 $profile['photo'] = $apcontact['photo'];
867                 // $profile['community']
868                 // $profile['keywords']
869                 // $profile['location']
870                 $profile['about'] = $apcontact['about'];
871                 $profile['batch'] = $apcontact['sharedinbox'];
872                 $profile['notify'] = $apcontact['inbox'];
873                 $profile['poll'] = $apcontact['outbox'];
874                 $profile['pubkey'] = $apcontact['pubkey'];
875                 $profile['baseurl'] = $apcontact['baseurl'];
876
877                 // Remove all "null" fields
878                 foreach ($profile as $field => $content) {
879                         if (is_null($content)) {
880                                 unset($profile[$field]);
881                         }
882                 }
883
884                 return $profile;
885         }
886
887         /**
888          * @brief 
889          *
890          * @param $body
891          * @param $header
892          * @param integer $uid User ID
893          */
894         public static function processInbox($body, $header, $uid)
895         {
896                 $http_signer = HTTPSignature::getSigner($body, $header);
897                 if (empty($http_signer)) {
898                         logger('Invalid HTTP signature, message will be discarded.', LOGGER_DEBUG);
899                         return;
900                 } else {
901                         logger('HTTP signature is signed by ' . $http_signer, LOGGER_DEBUG);
902                 }
903
904                 $activity = json_decode($body, true);
905
906                 $actor = JsonLD::fetchElement($activity, 'actor', 'id');
907                 logger('Message for user ' . $uid . ' is from actor ' . $actor, LOGGER_DEBUG);
908
909                 if (empty($activity)) {
910                         logger('Invalid body.', LOGGER_DEBUG);
911                         return;
912                 }
913
914                 if (LDSignature::isSigned($activity)) {
915                         $ld_signer = LDSignature::getSigner($activity);
916                         if (empty($ld_signer)) {
917                                 logger('Invalid JSON-LD signature from ' . $actor, LOGGER_DEBUG);
918                         }
919                         if (!empty($ld_signer && ($actor == $http_signer))) {
920                                 logger('The HTTP and the JSON-LD signature belong to ' . $ld_signer, LOGGER_DEBUG);
921                                 $trust_source = true;
922                         } elseif (!empty($ld_signer)) {
923                                 logger('JSON-LD signature is signed by ' . $ld_signer, LOGGER_DEBUG);
924                                 $trust_source = true;
925                         } elseif ($actor == $http_signer) {
926                                 logger('Bad JSON-LD signature, but HTTP signer fits the actor.', LOGGER_DEBUG);
927                                 $trust_source = true;
928                         } else {
929                                 logger('Invalid JSON-LD signature and the HTTP signer is different.', LOGGER_DEBUG);
930                                 $trust_source = false;
931                         }
932                 } elseif ($actor == $http_signer) {
933                         logger('Trusting post without JSON-LD signature, The actor fits the HTTP signer.', LOGGER_DEBUG);
934                         $trust_source = true;
935                 } else {
936                         logger('No JSON-LD signature, different actor.', LOGGER_DEBUG);
937                         $trust_source = false;
938                 }
939
940                 self::processActivity($activity, $body, $uid, $trust_source);
941         }
942
943         /**
944          * @brief 
945          *
946          * @param $url
947          * @param integer $uid User ID
948          */
949         public static function fetchOutbox($url, $uid)
950         {
951                 $data = self::fetchContent($url);
952                 if (empty($data)) {
953                         return;
954                 }
955
956                 if (!empty($data['orderedItems'])) {
957                         $items = $data['orderedItems'];
958                 } elseif (!empty($data['first']['orderedItems'])) {
959                         $items = $data['first']['orderedItems'];
960                 } elseif (!empty($data['first'])) {
961                         self::fetchOutbox($data['first'], $uid);
962                         return;
963                 } else {
964                         $items = [];
965                 }
966
967                 foreach ($items as $activity) {
968                         self::processActivity($activity, '', $uid, true);
969                 }
970         }
971
972         /**
973          * @brief 
974          *
975          * @param array $activity
976          * @param integer $uid User ID
977          * @param $trust_source
978          *
979          * @return 
980          */
981         private static function prepareObjectData($activity, $uid, &$trust_source)
982         {
983                 $actor = JsonLD::fetchElement($activity, 'actor', 'id');
984                 if (empty($actor)) {
985                         logger('Empty actor', LOGGER_DEBUG);
986                         return [];
987                 }
988
989                 // Fetch all receivers from to, cc, bto and bcc
990                 $receivers = self::getReceivers($activity, $actor);
991
992                 // When it is a delivery to a personal inbox we add that user to the receivers
993                 if (!empty($uid)) {
994                         $owner = User::getOwnerDataById($uid);
995                         $additional = ['uid:' . $uid => $uid];
996                         $receivers = array_merge($receivers, $additional);
997                 }
998
999                 logger('Receivers: ' . json_encode($receivers), LOGGER_DEBUG);
1000
1001                 $object_id = JsonLD::fetchElement($activity, 'object', 'id');
1002                 if (empty($object_id)) {
1003                         logger('No object found', LOGGER_DEBUG);
1004                         return [];
1005                 }
1006
1007                 // Fetch the content only on activities where this matters
1008                 if (in_array($activity['type'], ['Create', 'Announce'])) {
1009                         $object_data = self::fetchObject($object_id, $activity['object'], $trust_source);
1010                         if (empty($object_data)) {
1011                                 logger("Object data couldn't be processed", LOGGER_DEBUG);
1012                                 return [];
1013                         }
1014                         // We had been able to retrieve the object data - so we can trust the source
1015                         $trust_source = true;
1016                 } elseif (in_array($activity['type'], ['Like', 'Dislike'])) {
1017                         // Create a mostly empty array out of the activity data (instead of the object).
1018                         // This way we later don't have to check for the existence of ech individual array element.
1019                         $object_data = self::ProcessObject($activity);
1020                         $object_data['name'] = $activity['type'];
1021                         $object_data['author'] = $activity['actor'];
1022                         $object_data['object'] = $object_id;
1023                         $object_data['object_type'] = ''; // Since we don't fetch the object, we don't know the type
1024                 } else {
1025                         $object_data = [];
1026                         $object_data['id'] = $activity['id'];
1027                         $object_data['object'] = $activity['object'];
1028                         $object_data['object_type'] = JsonLD::fetchElement($activity, 'object', 'type');
1029                 }
1030
1031                 $object_data = self::addActivityFields($object_data, $activity);
1032
1033                 $object_data['type'] = $activity['type'];
1034                 $object_data['owner'] = $actor;
1035                 $object_data['receiver'] = array_merge(defaults($object_data, 'receiver', []), $receivers);
1036
1037                 logger('Processing ' . $object_data['type'] . ' ' . $object_data['object_type'] . ' ' . $object_data['id'], LOGGER_DEBUG);
1038
1039                 return $object_data;
1040         }
1041
1042         /**
1043          * @brief 
1044          *
1045          * @param array $activity
1046          * @param $body
1047          * @param integer $uid User ID
1048          * @param $trust_source
1049          */
1050         private static function processActivity($activity, $body = '', $uid = null, $trust_source = false)
1051         {
1052                 if (empty($activity['type'])) {
1053                         logger('Empty type', LOGGER_DEBUG);
1054                         return;
1055                 }
1056
1057                 if (empty($activity['object'])) {
1058                         logger('Empty object', LOGGER_DEBUG);
1059                         return;
1060                 }
1061
1062                 if (empty($activity['actor'])) {
1063                         logger('Empty actor', LOGGER_DEBUG);
1064                         return;
1065
1066                 }
1067
1068                 // $trust_source is called by reference and is set to true if the content was retrieved successfully
1069                 $object_data = self::prepareObjectData($activity, $uid, $trust_source);
1070                 if (empty($object_data)) {
1071                         logger('No object data found', LOGGER_DEBUG);
1072                         return;
1073                 }
1074
1075                 if (!$trust_source) {
1076                         logger('No trust for activity type "' . $activity['type'] . '", so we quit now.', LOGGER_DEBUG);
1077                 }
1078
1079                 switch ($activity['type']) {
1080                         case 'Create':
1081                         case 'Announce':
1082                                 self::createItem($object_data, $body);
1083                                 break;
1084
1085                         case 'Like':
1086                                 self::likeItem($object_data, $body);
1087                                 break;
1088
1089                         case 'Dislike':
1090                                 self::dislikeItem($object_data, $body);
1091                                 break;
1092
1093                         case 'Update':
1094                                 if (in_array($object_data['object_type'], ['Person', 'Organization', 'Service', 'Group', 'Application'])) {
1095                                         self::updatePerson($object_data, $body);
1096                                 }
1097                                 break;
1098
1099                         case 'Delete':
1100                                 break;
1101
1102                         case 'Follow':
1103                                 self::followUser($object_data);
1104                                 break;
1105
1106                         case 'Accept':
1107                                 if ($object_data['object_type'] == 'Follow') {
1108                                         self::acceptFollowUser($object_data);
1109                                 }
1110                                 break;
1111
1112                         case 'Undo':
1113                                 if ($object_data['object_type'] == 'Follow') {
1114                                         self::undoFollowUser($object_data);
1115                                 } elseif (in_array($object_data['object_type'], ['Like', 'Dislike', 'Accept', 'Reject', 'TentativeAccept'])) {
1116                                         self::undoActivity($object_data);
1117                                 }
1118                                 break;
1119
1120                         default:
1121                                 logger('Unknown activity: ' . $activity['type'], LOGGER_DEBUG);
1122                                 break;
1123                 }
1124         }
1125
1126         /**
1127          * @brief 
1128          *
1129          * @param array $activity
1130          * @param $actor
1131          *
1132          * @return 
1133          */
1134         private static function getReceivers($activity, $actor)
1135         {
1136                 $receivers = [];
1137
1138                 // When it is an answer, we inherite the receivers from the parent
1139                 $replyto = JsonLD::fetchElement($activity, 'inReplyTo', 'id');
1140                 if (!empty($replyto)) {
1141                         $parents = Item::select(['uid'], ['uri' => $replyto]);
1142                         while ($parent = Item::fetch($parents)) {
1143                                 $receivers['uid:' . $parent['uid']] = $parent['uid'];
1144                         }
1145                 }
1146
1147                 if (!empty($actor)) {
1148                         $profile = APContact::getProfileByURL($actor);
1149                         $followers = defaults($profile, 'followers', '');
1150
1151                         logger('Actor: ' . $actor . ' - Followers: ' . $followers, LOGGER_DEBUG);
1152                 } else {
1153                         logger('Empty actor', LOGGER_DEBUG);
1154                         $followers = '';
1155                 }
1156
1157                 $elements = ['to', 'cc', 'bto', 'bcc'];
1158                 foreach ($elements as $element) {
1159                         if (empty($activity[$element])) {
1160                                 continue;
1161                         }
1162
1163                         // The receiver can be an arror or a string
1164                         if (is_string($activity[$element])) {
1165                                 $activity[$element] = [$activity[$element]];
1166                         }
1167
1168                         foreach ($activity[$element] as $receiver) {
1169                                 if ($receiver == self::PUBLIC) {
1170                                         $receivers['uid:0'] = 0;
1171                                 }
1172
1173                                 if (($receiver == self::PUBLIC) && !empty($actor)) {
1174                                         // This will most likely catch all OStatus connections to Mastodon
1175                                         $condition = ['alias' => [$actor, normalise_link($actor)], 'rel' => [Contact::SHARING, Contact::FRIEND]];
1176                                         $contacts = DBA::select('contact', ['uid'], $condition);
1177                                         while ($contact = DBA::fetch($contacts)) {
1178                                                 if ($contact['uid'] != 0) {
1179                                                         $receivers['uid:' . $contact['uid']] = $contact['uid'];
1180                                                 }
1181                                         }
1182                                         DBA::close($contacts);
1183                                 }
1184
1185                                 if (in_array($receiver, [$followers, self::PUBLIC]) && !empty($actor)) {
1186                                         $condition = ['nurl' => normalise_link($actor), 'rel' => [Contact::SHARING, Contact::FRIEND],
1187                                                 'network' => Protocol::ACTIVITYPUB];
1188                                         $contacts = DBA::select('contact', ['uid'], $condition);
1189                                         while ($contact = DBA::fetch($contacts)) {
1190                                                 if ($contact['uid'] != 0) {
1191                                                         $receivers['uid:' . $contact['uid']] = $contact['uid'];
1192                                                 }
1193                                         }
1194                                         DBA::close($contacts);
1195                                         continue;
1196                                 }
1197
1198                                 $condition = ['self' => true, 'nurl' => normalise_link($receiver)];
1199                                 $contact = DBA::selectFirst('contact', ['uid'], $condition);
1200                                 if (!DBA::isResult($contact)) {
1201                                         continue;
1202                                 }
1203                                 $receivers['uid:' . $contact['uid']] = $contact['uid'];
1204                         }
1205                 }
1206
1207                 self::switchContacts($receivers, $actor);
1208
1209                 return $receivers;
1210         }
1211
1212         /**
1213          * @brief 
1214          *
1215          * @param $cid
1216          * @param integer $uid User ID
1217          * @param $url
1218          */
1219         private static function switchContact($cid, $uid, $url)
1220         {
1221                 $profile = ActivityPub::probeProfile($url);
1222                 if (empty($profile)) {
1223                         return;
1224                 }
1225
1226                 logger('Switch contact ' . $cid . ' (' . $profile['url'] . ') for user ' . $uid . ' from OStatus to ActivityPub');
1227
1228                 $photo = $profile['photo'];
1229                 unset($profile['photo']);
1230                 unset($profile['baseurl']);
1231
1232                 $profile['nurl'] = normalise_link($profile['url']);
1233                 DBA::update('contact', $profile, ['id' => $cid]);
1234
1235                 Contact::updateAvatar($photo, $uid, $cid);
1236         }
1237
1238         /**
1239          * @brief 
1240          *
1241          * @param $receivers
1242          * @param $actor
1243          */
1244         private static function switchContacts($receivers, $actor)
1245         {
1246                 if (empty($actor)) {
1247                         return;
1248                 }
1249
1250                 foreach ($receivers as $receiver) {
1251                         $contact = DBA::selectFirst('contact', ['id'], ['uid' => $receiver, 'network' => Protocol::OSTATUS, 'nurl' => normalise_link($actor)]);
1252                         if (DBA::isResult($contact)) {
1253                                 self::switchContact($contact['id'], $receiver, $actor);
1254                         }
1255
1256                         $contact = DBA::selectFirst('contact', ['id'], ['uid' => $receiver, 'network' => Protocol::OSTATUS, 'alias' => [normalise_link($actor), $actor]]);
1257                         if (DBA::isResult($contact)) {
1258                                 self::switchContact($contact['id'], $receiver, $actor);
1259                         }
1260                 }
1261         }
1262
1263         /**
1264          * @brief 
1265          *
1266          * @param $object_data
1267          * @param array $activity
1268          *
1269          * @return 
1270          */
1271         private static function addActivityFields($object_data, $activity)
1272         {
1273                 if (!empty($activity['published']) && empty($object_data['published'])) {
1274                         $object_data['published'] = $activity['published'];
1275                 }
1276
1277                 if (!empty($activity['updated']) && empty($object_data['updated'])) {
1278                         $object_data['updated'] = $activity['updated'];
1279                 }
1280
1281                 if (!empty($activity['inReplyTo']) && empty($object_data['parent-uri'])) {
1282                         $object_data['parent-uri'] = JsonLD::fetchElement($activity, 'inReplyTo', 'id');
1283                 }
1284
1285                 if (!empty($activity['instrument'])) {
1286                         $object_data['service'] = JsonLD::fetchElement($activity, 'instrument', 'name', 'type', 'Service');
1287                 }
1288                 return $object_data;
1289         }
1290
1291         /**
1292          * @brief 
1293          *
1294          * @param $object_id
1295          * @param $object
1296          * @param $trust_source
1297          *
1298          * @return 
1299          */
1300         private static function fetchObject($object_id, $object = [], $trust_source = false)
1301         {
1302                 if (!$trust_source || is_string($object)) {
1303                         $data = self::fetchContent($object_id);
1304                         if (empty($data)) {
1305                                 logger('Empty content for ' . $object_id . ', check if content is available locally.', LOGGER_DEBUG);
1306                                 $data = $object_id;
1307                         } else {
1308                                 logger('Fetched content for ' . $object_id, LOGGER_DEBUG);
1309                         }
1310                 } else {
1311                         logger('Using original object for url ' . $object_id, LOGGER_DEBUG);
1312                         $data = $object;
1313                 }
1314
1315                 if (is_string($data)) {
1316                         $item = Item::selectFirst([], ['uri' => $data]);
1317                         if (!DBA::isResult($item)) {
1318                                 logger('Object with url ' . $data . ' was not found locally.', LOGGER_DEBUG);
1319                                 return false;
1320                         }
1321                         logger('Using already stored item for url ' . $object_id, LOGGER_DEBUG);
1322                         $data = self::CreateNote($item);
1323                 }
1324
1325                 if (empty($data['type'])) {
1326                         logger('Empty type', LOGGER_DEBUG);
1327                         return false;
1328                 }
1329
1330                 switch ($data['type']) {
1331                         case 'Note':
1332                         case 'Article':
1333                         case 'Video':
1334                                 return self::ProcessObject($data);
1335
1336                         case 'Announce':
1337                                 if (empty($data['object'])) {
1338                                         return false;
1339                                 }
1340                                 return self::fetchObject($data['object']);
1341
1342                         case 'Person':
1343                         case 'Tombstone':
1344                                 break;
1345
1346                         default:
1347                                 logger('Unknown object type: ' . $data['type'], LOGGER_DEBUG);
1348                                 break;
1349                 }
1350         }
1351
1352         /**
1353          * @brief 
1354          *
1355          * @param $object
1356          *
1357          * @return 
1358          */
1359         private static function ProcessObject(&$object)
1360         {
1361                 if (empty($object['id'])) {
1362                         return false;
1363                 }
1364
1365                 $object_data = [];
1366                 $object_data['object_type'] = $object['type'];
1367                 $object_data['id'] = $object['id'];
1368
1369                 if (!empty($object['inReplyTo'])) {
1370                         $object_data['reply-to-id'] = JsonLD::fetchElement($object, 'inReplyTo', 'id');
1371                 } else {
1372                         $object_data['reply-to-id'] = $object_data['id'];
1373                 }
1374
1375                 $object_data['published'] = defaults($object, 'published', null);
1376                 $object_data['updated'] = defaults($object, 'updated', $object_data['published']);
1377
1378                 if (empty($object_data['published']) && !empty($object_data['updated'])) {
1379                         $object_data['published'] = $object_data['updated'];
1380                 }
1381
1382                 $actor = JsonLD::fetchElement($object, 'attributedTo', 'id');
1383                 if (empty($actor)) {
1384                         $actor = defaults($object, 'actor', null);
1385                 }
1386
1387                 $object_data['diaspora:guid'] = defaults($object, 'diaspora:guid', null);
1388                 $object_data['owner'] = $object_data['author'] = $actor;
1389                 $object_data['context'] = defaults($object, 'context', null);
1390                 $object_data['conversation'] = defaults($object, 'conversation', null);
1391                 $object_data['sensitive'] = defaults($object, 'sensitive', null);
1392                 $object_data['name'] = defaults($object, 'title', null);
1393                 $object_data['name'] = defaults($object, 'name', $object_data['name']);
1394                 $object_data['summary'] = defaults($object, 'summary', null);
1395                 $object_data['content'] = defaults($object, 'content', null);
1396                 $object_data['source'] = defaults($object, 'source', null);
1397                 $object_data['location'] = JsonLD::fetchElement($object, 'location', 'name', 'type', 'Place');
1398                 $object_data['attachments'] = defaults($object, 'attachment', null);
1399                 $object_data['tags'] = defaults($object, 'tag', null);
1400                 $object_data['service'] = JsonLD::fetchElement($object, 'instrument', 'name', 'type', 'Service');
1401                 $object_data['alternate-url'] = JsonLD::fetchElement($object, 'url', 'href');
1402                 $object_data['receiver'] = self::getReceivers($object, $object_data['owner']);
1403
1404                 // Common object data:
1405
1406                 // Unhandled
1407                 // @context, type, actor, signature, mediaType, duration, replies, icon
1408
1409                 // Also missing: (Defined in the standard, but currently unused)
1410                 // audience, preview, endTime, startTime, generator, image
1411
1412                 // Data in Notes:
1413
1414                 // Unhandled
1415                 // contentMap, announcement_count, announcements, context_id, likes, like_count
1416                 // inReplyToStatusId, shares, quoteUrl, statusnetConversationId
1417
1418                 // Data in video:
1419
1420                 // To-Do?
1421                 // category, licence, language, commentsEnabled
1422
1423                 // Unhandled
1424                 // views, waitTranscoding, state, support, subtitleLanguage
1425                 // likes, dislikes, shares, comments
1426
1427                 return $object_data;
1428         }
1429
1430         /**
1431          * @brief Converts mentions from Pleroma into the Friendica format
1432          *
1433          * @param string $body
1434          *
1435          * @return converted body
1436          */
1437         private static function convertMentions($body)
1438         {
1439                 $URLSearchString = "^\[\]";
1440                 $body = preg_replace("/\[url\=([$URLSearchString]*)\]([#@!])(.*?)\[\/url\]/ism", '$2[url=$1]$3[/url]', $body);
1441
1442                 return $body;
1443         }
1444
1445         /**
1446          * @brief Constructs a string with tags for a given tag array
1447          *
1448          * @param array $tags
1449          * @param boolean $sensitive
1450          *
1451          * @return string with tags
1452          */
1453         private static function constructTagList($tags, $sensitive)
1454         {
1455                 if (empty($tags)) {
1456                         return '';
1457                 }
1458
1459                 $tag_text = '';
1460                 foreach ($tags as $tag) {
1461                         if (in_array($tag['type'], ['Mention', 'Hashtag'])) {
1462                                 if (!empty($tag_text)) {
1463                                         $tag_text .= ',';
1464                                 }
1465
1466                                 $tag_text .= substr($tag['name'], 0, 1) . '[url=' . $tag['href'] . ']' . substr($tag['name'], 1) . '[/url]';
1467                         }
1468                 }
1469
1470                 /// @todo add nsfw for $sensitive
1471
1472                 return $tag_text;
1473         }
1474
1475         /**
1476          * @brief 
1477          *
1478          * @param $attachments
1479          * @param array $item
1480          *
1481          * @return item array
1482          */
1483         private static function constructAttachList($attachments, $item)
1484         {
1485                 if (empty($attachments)) {
1486                         return $item;
1487                 }
1488
1489                 foreach ($attachments as $attach) {
1490                         $filetype = strtolower(substr($attach['mediaType'], 0, strpos($attach['mediaType'], '/')));
1491                         if ($filetype == 'image') {
1492                                 $item['body'] .= "\n[img]".$attach['url'].'[/img]';
1493                         } else {
1494                                 if (!empty($item["attach"])) {
1495                                         $item["attach"] .= ',';
1496                                 } else {
1497                                         $item["attach"] = '';
1498                                 }
1499                                 if (!isset($attach['length'])) {
1500                                         $attach['length'] = "0";
1501                                 }
1502                                 $item["attach"] .= '[attach]href="'.$attach['url'].'" length="'.$attach['length'].'" type="'.$attach['mediaType'].'" title="'.defaults($attach, 'name', '').'"[/attach]';
1503                         }
1504                 }
1505
1506                 return $item;
1507         }
1508
1509         /**
1510          * @brief 
1511          *
1512          * @param array $activity
1513          * @param $body
1514          */
1515         private static function createItem($activity, $body)
1516         {
1517                 $item = [];
1518                 $item['verb'] = ACTIVITY_POST;
1519                 $item['parent-uri'] = $activity['reply-to-id'];
1520
1521                 if ($activity['reply-to-id'] == $activity['id']) {
1522                         $item['gravity'] = GRAVITY_PARENT;
1523                         $item['object-type'] = ACTIVITY_OBJ_NOTE;
1524                 } else {
1525                         $item['gravity'] = GRAVITY_COMMENT;
1526                         $item['object-type'] = ACTIVITY_OBJ_COMMENT;
1527                 }
1528
1529                 if (($activity['id'] != $activity['reply-to-id']) && !Item::exists(['uri' => $activity['reply-to-id']])) {
1530                         logger('Parent ' . $activity['reply-to-id'] . ' not found. Try to refetch it.');
1531                         self::fetchMissingActivity($activity['reply-to-id'], $activity);
1532                 }
1533
1534                 self::postItem($activity, $item, $body);
1535         }
1536
1537         /**
1538          * @brief 
1539          *
1540          * @param array $activity
1541          * @param $body
1542          */
1543         private static function likeItem($activity, $body)
1544         {
1545                 $item = [];
1546                 $item['verb'] = ACTIVITY_LIKE;
1547                 $item['parent-uri'] = $activity['object'];
1548                 $item['gravity'] = GRAVITY_ACTIVITY;
1549                 $item['object-type'] = ACTIVITY_OBJ_NOTE;
1550
1551                 self::postItem($activity, $item, $body);
1552         }
1553
1554         /**
1555          * @brief 
1556          *
1557          * @param array $activity
1558          * @param $body
1559          */
1560         private static function dislikeItem($activity, $body)
1561         {
1562                 $item = [];
1563                 $item['verb'] = ACTIVITY_DISLIKE;
1564                 $item['parent-uri'] = $activity['object'];
1565                 $item['gravity'] = GRAVITY_ACTIVITY;
1566                 $item['object-type'] = ACTIVITY_OBJ_NOTE;
1567
1568                 self::postItem($activity, $item, $body);
1569         }
1570
1571         /**
1572          * @brief 
1573          *
1574          * @param array $activity
1575          * @param array $item
1576          * @param $body
1577          */
1578         private static function postItem($activity, $item, $body)
1579         {
1580                 /// @todo What to do with $activity['context']?
1581
1582                 if (($item['gravity'] != GRAVITY_PARENT) && !Item::exists(['uri' => $item['parent-uri']])) {
1583                         logger('Parent ' . $item['parent-uri'] . ' not found, message will be discarded.', LOGGER_DEBUG);
1584                         return;
1585                 }
1586
1587                 $item['network'] = Protocol::ACTIVITYPUB;
1588                 $item['private'] = !in_array(0, $activity['receiver']);
1589                 $item['author-id'] = Contact::getIdForURL($activity['author'], 0, true);
1590                 $item['owner-id'] = Contact::getIdForURL($activity['owner'], 0, true);
1591                 $item['uri'] = $activity['id'];
1592                 $item['created'] = $activity['published'];
1593                 $item['edited'] = $activity['updated'];
1594                 $item['guid'] = $activity['diaspora:guid'];
1595                 $item['title'] = HTML::toBBCode($activity['name']);
1596                 $item['content-warning'] = HTML::toBBCode($activity['summary']);
1597                 $item['body'] = self::convertMentions(HTML::toBBCode($activity['content']));
1598                 $item['location'] = $activity['location'];
1599                 $item['tag'] = self::constructTagList($activity['tags'], $activity['sensitive']);
1600                 $item['app'] = $activity['service'];
1601                 $item['plink'] = defaults($activity, 'alternate-url', $item['uri']);
1602
1603                 $item = self::constructAttachList($activity['attachments'], $item);
1604
1605                 $source = JsonLD::fetchElement($activity, 'source', 'content', 'mediaType', 'text/bbcode');
1606                 if (!empty($source)) {
1607                         $item['body'] = $source;
1608                 }
1609
1610                 $item['protocol'] = Conversation::PARCEL_ACTIVITYPUB;
1611                 $item['source'] = $body;
1612                 $item['conversation-href'] = $activity['context'];
1613                 $item['conversation-uri'] = $activity['conversation'];
1614
1615                 foreach ($activity['receiver'] as $receiver) {
1616                         $item['uid'] = $receiver;
1617                         $item['contact-id'] = Contact::getIdForURL($activity['author'], $receiver, true);
1618
1619                         if (($receiver != 0) && empty($item['contact-id'])) {
1620                                 $item['contact-id'] = Contact::getIdForURL($activity['author'], 0, true);
1621                         }
1622
1623                         $item_id = Item::insert($item);
1624                         logger('Storing for user ' . $item['uid'] . ': ' . $item_id);
1625                 }
1626         }
1627
1628         /**
1629          * @brief 
1630          *
1631          * @param $url
1632          * @param $child
1633          */
1634         private static function fetchMissingActivity($url, $child)
1635         {
1636                 if (Config::get('system', 'ostatus_full_threads')) {
1637                         return;
1638                 }
1639
1640                 $object = ActivityPub::fetchContent($url);
1641                 if (empty($object)) {
1642                         logger('Activity ' . $url . ' was not fetchable, aborting.');
1643                         return;
1644                 }
1645
1646                 $activity = [];
1647                 $activity['@context'] = $object['@context'];
1648                 unset($object['@context']);
1649                 $activity['id'] = $object['id'];
1650                 $activity['to'] = defaults($object, 'to', []);
1651                 $activity['cc'] = defaults($object, 'cc', []);
1652                 $activity['actor'] = $child['author'];
1653                 $activity['object'] = $object;
1654                 $activity['published'] = $object['published'];
1655                 $activity['type'] = 'Create';
1656
1657                 self::processActivity($activity);
1658                 logger('Activity ' . $url . ' had been fetched and processed.');
1659         }
1660
1661         /**
1662          * @brief Returns the user id of a given profile url
1663          *
1664          * @param string $profile
1665          *
1666          * @return integer user id
1667          */
1668         private static function getUserOfProfile($profile)
1669         {
1670                 $self = DBA::selectFirst('contact', ['uid'], ['nurl' => normalise_link($profile), 'self' => true]);
1671                 if (!DBA::isResult($self)) {
1672                         return false;
1673                 } else {
1674                         return $self['uid'];
1675                 }
1676         }
1677
1678         /**
1679          * @brief perform a "follow" request
1680          *
1681          * @param array $activity
1682          */
1683         private static function followUser($activity)
1684         {
1685                 $actor = JsonLD::fetchElement($activity, 'object', 'id');
1686                 $uid = self::getUserOfProfile($actor);
1687                 if (empty($uid)) {
1688                         return;
1689                 }
1690
1691                 $owner = User::getOwnerDataById($uid);
1692
1693                 $cid = Contact::getIdForURL($activity['owner'], $uid);
1694                 if (!empty($cid)) {
1695                         $contact = DBA::selectFirst('contact', [], ['id' => $cid]);
1696                 } else {
1697                         $contact = false;
1698                 }
1699
1700                 $item = ['author-id' => Contact::getIdForURL($activity['owner']),
1701                         'author-link' => $activity['owner']];
1702
1703                 Contact::addRelationship($owner, $contact, $item);
1704                 $cid = Contact::getIdForURL($activity['owner'], $uid);
1705                 if (empty($cid)) {
1706                         return;
1707                 }
1708
1709                 $contact = DBA::selectFirst('contact', ['network'], ['id' => $cid]);
1710                 if ($contact['network'] != Protocol::ACTIVITYPUB) {
1711                         Contact::updateFromProbe($cid, Protocol::ACTIVITYPUB);
1712                 }
1713
1714                 DBA::update('contact', ['hub-verify' => $activity['id']], ['id' => $cid]);
1715                 logger('Follow user ' . $uid . ' from contact ' . $cid . ' with id ' . $activity['id']);
1716         }
1717
1718         /**
1719          * @brief Update the given profile
1720          *
1721          * @param array $activity
1722          */
1723         private static function updatePerson($activity)
1724         {
1725                 if (empty($activity['object']['id'])) {
1726                         return;
1727                 }
1728
1729                 logger('Updating profile for ' . $activity['object']['id'], LOGGER_DEBUG);
1730                 APContact::getProfileByURL($activity['object']['id'], true);
1731         }
1732
1733         /**
1734          * @brief Accept a follow request
1735          *
1736          * @param array $activity
1737          */
1738         private static function acceptFollowUser($activity)
1739         {
1740                 $actor = JsonLD::fetchElement($activity, 'object', 'actor');
1741                 $uid = self::getUserOfProfile($actor);
1742                 if (empty($uid)) {
1743                         return;
1744                 }
1745
1746                 $owner = User::getOwnerDataById($uid);
1747
1748                 $cid = Contact::getIdForURL($activity['owner'], $uid);
1749                 if (empty($cid)) {
1750                         logger('No contact found for ' . $activity['owner'], LOGGER_DEBUG);
1751                         return;
1752                 }
1753
1754                 $fields = ['pending' => false];
1755
1756                 $contact = DBA::selectFirst('contact', ['rel'], ['id' => $cid]);
1757                 if ($contact['rel'] == Contact::FOLLOWER) {
1758                         $fields['rel'] = Contact::FRIEND;
1759                 }
1760
1761                 $condition = ['id' => $cid];
1762                 DBA::update('contact', $fields, $condition);
1763                 logger('Accept contact request from contact ' . $cid . ' for user ' . $uid, LOGGER_DEBUG);
1764         }
1765
1766         /**
1767          * @brief Undo activity like "like" or "dislike"
1768          *
1769          * @param array $activity
1770          */
1771         private static function undoActivity($activity)
1772         {
1773                 $activity_url = JsonLD::fetchElement($activity, 'object', 'id');
1774                 if (empty($activity_url)) {
1775                         return;
1776                 }
1777
1778                 $actor = JsonLD::fetchElement($activity, 'object', 'actor');
1779                 if (empty($actor)) {
1780                         return;
1781                 }
1782
1783                 $author_id = Contact::getIdForURL($actor);
1784                 if (empty($author_id)) {
1785                         return;
1786                 }
1787
1788                 Item::delete(['uri' => $activity_url, 'author-id' => $author_id, 'gravity' => GRAVITY_ACTIVITY]);
1789         }
1790
1791         /**
1792          * @brief Activity to remove a follower
1793          *
1794          * @param array $activity
1795          */
1796         private static function undoFollowUser($activity)
1797         {
1798                 $object = JsonLD::fetchElement($activity, 'object', 'object');
1799                 $uid = self::getUserOfProfile($object);
1800                 if (empty($uid)) {
1801                         return;
1802                 }
1803
1804                 $owner = User::getOwnerDataById($uid);
1805
1806                 $cid = Contact::getIdForURL($activity['owner'], $uid);
1807                 if (empty($cid)) {
1808                         logger('No contact found for ' . $activity['owner'], LOGGER_DEBUG);
1809                         return;
1810                 }
1811
1812                 $contact = DBA::selectFirst('contact', [], ['id' => $cid]);
1813                 if (!DBA::isResult($contact)) {
1814                         return;
1815                 }
1816
1817                 Contact::removeFollower($owner, $contact);
1818                 logger('Undo following request from contact ' . $cid . ' for user ' . $uid, LOGGER_DEBUG);
1819         }
1820 }