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