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