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