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