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