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