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