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