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