]> git.mxchange.org Git - friendica.git/blob - src/Protocol/ActivityPub.php
Fetch the receiver from the parent posting as well
[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                 // When it is an answer, we inherite the receivers from the parent
833                 $replyto = JsonLD::fetchElement($activity, 'inReplyTo', 'id');
834                 if (!empty($replyto)) {
835                         $parents = Item::select(['uid'], ['uri' => $replyto]);
836                         while ($parent = Item::fetch($parents)) {
837                                 $receivers['uid:' . $parent['uid']] = $parent['uid'];
838                         }
839                 }
840
841                 if (!empty($actor)) {
842                         $profile = self::fetchprofile($actor);
843                         $followers = defaults($profile, 'followers', '');
844
845                         logger('Actor: ' . $actor . ' - Followers: ' . $followers, LOGGER_DEBUG);
846                 } else {
847                         logger('Empty actor', LOGGER_DEBUG);
848                         $followers = '';
849                 }
850
851                 $elements = ['to', 'cc', 'bto', 'bcc'];
852                 foreach ($elements as $element) {
853                         if (empty($activity[$element])) {
854                                 continue;
855                         }
856
857                         // The receiver can be an arror or a string
858                         if (is_string($activity[$element])) {
859                                 $activity[$element] = [$activity[$element]];
860                         }
861
862                         foreach ($activity[$element] as $receiver) {
863                                 if ($receiver == self::PUBLIC) {
864                                         $receivers['uid:0'] = 0;
865                                 }
866
867                                 if (($receiver == self::PUBLIC) && !empty($actor)) {
868                                         // This will most likely catch all OStatus connections to Mastodon
869                                         $condition = ['alias' => [$actor, normalise_link($actor)], 'rel' => [Contact::SHARING, Contact::FRIEND]];
870                                         $contacts = DBA::select('contact', ['uid'], $condition);
871                                         while ($contact = DBA::fetch($contacts)) {
872                                                 if ($contact['uid'] != 0) {
873                                                         $receivers['uid:' . $contact['uid']] = $contact['uid'];
874                                                 }
875                                         }
876                                         DBA::close($contacts);
877                                 }
878
879                                 if (in_array($receiver, [$followers, self::PUBLIC]) && !empty($actor)) {
880                                         $condition = ['nurl' => normalise_link($actor), 'rel' => [Contact::SHARING, Contact::FRIEND],
881                                                 'network' => Protocol::ACTIVITYPUB];
882                                         $contacts = DBA::select('contact', ['uid'], $condition);
883                                         while ($contact = DBA::fetch($contacts)) {
884                                                 if ($contact['uid'] != 0) {
885                                                         $receivers['uid:' . $contact['uid']] = $contact['uid'];
886                                                 }
887                                         }
888                                         DBA::close($contacts);
889                                         continue;
890                                 }
891
892                                 $condition = ['self' => true, 'nurl' => normalise_link($receiver)];
893                                 $contact = DBA::selectFirst('contact', ['uid'], $condition);
894                                 if (!DBA::isResult($contact)) {
895                                         continue;
896                                 }
897                                 $receivers['uid:' . $contact['uid']] = $contact['uid'];
898                         }
899                 }
900                 return $receivers;
901         }
902
903         private static function addActivityFields($object_data, $activity)
904         {
905                 if (!empty($activity['published']) && empty($object_data['published'])) {
906                         $object_data['published'] = $activity['published'];
907                 }
908
909                 if (!empty($activity['updated']) && empty($object_data['updated'])) {
910                         $object_data['updated'] = $activity['updated'];
911                 }
912
913                 if (!empty($activity['inReplyTo']) && empty($object_data['parent-uri'])) {
914                         $object_data['parent-uri'] = JsonLD::fetchElement($activity, 'inReplyTo', 'id');
915                 }
916
917                 if (!empty($activity['instrument'])) {
918                         $object_data['service'] = JsonLD::fetchElement($activity, 'instrument', 'name', 'type', 'Service');
919                 }
920                 return $object_data;
921         }
922
923         private static function fetchObject($object_url, $object = [], $unsigned = true)
924         {
925                 if ($unsigned) {
926                         $data = self::fetchContent($object_url);
927                         if (empty($data)) {
928                                 logger('Empty content for ' . $object_url . ', check if content is available locally.', LOGGER_DEBUG);
929                                 $data = $object_url;
930                                 $data = $object;
931                         }
932                 } else {
933                         logger('Using original object for url ' . $object_url, LOGGER_DEBUG);
934                         $data = $object;
935                 }
936
937                 if (is_string($data)) {
938                         $item = Item::selectFirst([], ['uri' => $data]);
939                         if (!DBA::isResult($item)) {
940                                 logger('Object with url ' . $data . ' was not found locally.', LOGGER_DEBUG);
941                                 return false;
942                         }
943                         logger('Using already stored item for url ' . $object_url, LOGGER_DEBUG);
944                         $data = self::createNote($item);
945                 }
946
947                 if (empty($data['type'])) {
948                         logger('Empty type', LOGGER_DEBUG);
949                         return false;
950                 } else {
951                         $type = $data['type'];
952                         logger('Type ' . $type, LOGGER_DEBUG);
953                 }
954
955                 if (in_array($type, ['Note', 'Article', 'Video'])) {
956                         $common = self::processCommonData($data);
957                 }
958
959                 switch ($type) {
960                         case 'Note':
961                                 return array_merge($common, self::processNote($data));
962                         case 'Article':
963                                 return array_merge($common, self::processArticle($data));
964                         case 'Video':
965                                 return array_merge($common, self::processVideo($data));
966
967                         case 'Announce':
968                                 if (empty($data['object'])) {
969                                         return false;
970                                 }
971                                 return self::fetchObject($data['object']);
972
973                         case 'Person':
974                         case 'Tombstone':
975                                 break;
976
977                         default:
978                                 logger('Unknown object type: ' . $data['type'], LOGGER_DEBUG);
979                                 break;
980                 }
981         }
982
983         private static function processCommonData(&$object)
984         {
985                 if (empty($object['id'])) {
986                         return false;
987                 }
988
989                 $object_data = [];
990                 $object_data['type'] = $object['type'];
991                 $object_data['uri'] = $object['id'];
992
993                 if (!empty($object['inReplyTo'])) {
994                         $object_data['reply-to-uri'] = JsonLD::fetchElement($object, 'inReplyTo', 'id');
995                 } else {
996                         $object_data['reply-to-uri'] = $object_data['uri'];
997                 }
998
999                 $object_data['published'] = defaults($object, 'published', null);
1000                 $object_data['updated'] = defaults($object, 'updated', $object_data['published']);
1001
1002                 if (empty($object_data['published']) && !empty($object_data['updated'])) {
1003                         $object_data['published'] = $object_data['updated'];
1004                 }
1005
1006                 $object_data['uuid'] = defaults($object, 'uuid', null);
1007                 $object_data['owner'] = $object_data['author'] = JsonLD::fetchElement($object, 'attributedTo', 'id');
1008                 $object_data['context'] = defaults($object, 'context', null);
1009                 $object_data['conversation'] = defaults($object, 'conversation', null);
1010                 $object_data['sensitive'] = defaults($object, 'sensitive', null);
1011                 $object_data['name'] = defaults($object, 'title', null);
1012                 $object_data['name'] = defaults($object, 'name', $object_data['name']);
1013                 $object_data['summary'] = defaults($object, 'summary', null);
1014                 $object_data['content'] = defaults($object, 'content', null);
1015                 $object_data['source'] = defaults($object, 'source', null);
1016                 $object_data['location'] = JsonLD::fetchElement($object, 'location', 'name', 'type', 'Place');
1017                 $object_data['attachments'] = defaults($object, 'attachment', null);
1018                 $object_data['tags'] = defaults($object, 'tag', null);
1019                 $object_data['service'] = JsonLD::fetchElement($object, 'instrument', 'name', 'type', 'Service');
1020                 $object_data['alternate-url'] = JsonLD::fetchElement($object, 'url', 'href');
1021                 $object_data['receiver'] = self::getReceivers($object, $object_data['owner']);
1022
1023                 // Unhandled
1024                 // @context, type, actor, signature, mediaType, duration, replies, icon
1025
1026                 // Also missing: (Defined in the standard, but currently unused)
1027                 // audience, preview, endTime, startTime, generator, image
1028
1029                 return $object_data;
1030         }
1031
1032         private static function processNote($object)
1033         {
1034                 $object_data = [];
1035
1036                 // To-Do?
1037                 // emoji, atomUri, inReplyToAtomUri
1038
1039                 // Unhandled
1040                 // contentMap, announcement_count, announcements, context_id, likes, like_count
1041                 // inReplyToStatusId, shares, quoteUrl, statusnetConversationId
1042
1043                 return $object_data;
1044         }
1045
1046         private static function processArticle($object)
1047         {
1048                 $object_data = [];
1049
1050                 return $object_data;
1051         }
1052
1053         private static function processVideo($object)
1054         {
1055                 $object_data = [];
1056
1057                 // To-Do?
1058                 // category, licence, language, commentsEnabled
1059
1060                 // Unhandled
1061                 // views, waitTranscoding, state, support, subtitleLanguage
1062                 // likes, dislikes, shares, comments
1063
1064                 return $object_data;
1065         }
1066
1067         private static function convertMentions($body)
1068         {
1069                 $URLSearchString = "^\[\]";
1070                 $body = preg_replace("/\[url\=([$URLSearchString]*)\]([#@!])(.*?)\[\/url\]/ism", '$2[url=$1]$3[/url]', $body);
1071
1072                 return $body;
1073         }
1074
1075         private static function constructTagList($tags, $sensitive)
1076         {
1077                 if (empty($tags)) {
1078                         return '';
1079                 }
1080
1081                 $tag_text = '';
1082                 foreach ($tags as $tag) {
1083                         if (in_array($tag['type'], ['Mention', 'Hashtag'])) {
1084                                 if (!empty($tag_text)) {
1085                                         $tag_text .= ',';
1086                                 }
1087
1088                                 if (empty($tag['href'])) {
1089                                         //$tag['href']
1090                                         logger('Blubb!');
1091                                 }
1092
1093                                 $tag_text .= substr($tag['name'], 0, 1) . '[url=' . $tag['href'] . ']' . substr($tag['name'], 1) . '[/url]';
1094                         }
1095                 }
1096
1097                 /// @todo add nsfw for $sensitive
1098
1099                 return $tag_text;
1100         }
1101
1102         private static function constructAttachList($attachments, $item)
1103         {
1104                 if (empty($attachments)) {
1105                         return $item;
1106                 }
1107
1108                 foreach ($attachments as $attach) {
1109                         $filetype = strtolower(substr($attach['mediaType'], 0, strpos($attach['mediaType'], '/')));
1110                         if ($filetype == 'image') {
1111                                 $item['body'] .= "\n[img]".$attach['url'].'[/img]';
1112                         } else {
1113                                 if (!empty($item["attach"])) {
1114                                         $item["attach"] .= ',';
1115                                 } else {
1116                                         $item["attach"] = '';
1117                                 }
1118                                 if (!isset($attach['length'])) {
1119                                         $attach['length'] = "0";
1120                                 }
1121                                 $item["attach"] .= '[attach]href="'.$attach['url'].'" length="'.$attach['length'].'" type="'.$attach['mediaType'].'" title="'.defaults($attach, 'name', '').'"[/attach]';
1122                         }
1123                 }
1124
1125                 return $item;
1126         }
1127
1128         private static function createItem($activity, $body)
1129         {
1130                 $item = [];
1131                 $item['verb'] = ACTIVITY_POST;
1132                 $item['parent-uri'] = $activity['reply-to-uri'];
1133
1134                 if ($activity['reply-to-uri'] == $activity['uri']) {
1135                         $item['gravity'] = GRAVITY_PARENT;
1136                         $item['object-type'] = ACTIVITY_OBJ_NOTE;
1137                 } else {
1138                         $item['gravity'] = GRAVITY_COMMENT;
1139                         $item['object-type'] = ACTIVITY_OBJ_COMMENT;
1140                 }
1141
1142                 if (($activity['uri'] != $activity['reply-to-uri']) && !Item::exists(['uri' => $activity['reply-to-uri']])) {
1143                         logger('Parent ' . $activity['reply-to-uri'] . ' not found. Try to refetch it.');
1144                         self::fetchMissingActivity($activity['reply-to-uri'], $activity);
1145                 }
1146
1147                 self::postItem($activity, $item, $body);
1148         }
1149
1150         private static function likeItem($activity, $body)
1151         {
1152                 $item = [];
1153                 $item['verb'] = ACTIVITY_LIKE;
1154                 $item['parent-uri'] = $activity['object'];
1155                 $item['gravity'] = GRAVITY_ACTIVITY;
1156                 $item['object-type'] = ACTIVITY_OBJ_NOTE;
1157
1158                 self::postItem($activity, $item, $body);
1159         }
1160
1161         private static function postItem($activity, $item, $body)
1162         {
1163                 /// @todo What to do with $activity['context']?
1164
1165                 $item['network'] = Protocol::ACTIVITYPUB;
1166                 $item['private'] = !in_array(0, $activity['receiver']);
1167                 $item['author-id'] = Contact::getIdForURL($activity['author'], 0, true);
1168                 $item['owner-id'] = Contact::getIdForURL($activity['owner'], 0, true);
1169                 $item['uri'] = $activity['uri'];
1170                 $item['created'] = $activity['published'];
1171                 $item['edited'] = $activity['updated'];
1172                 $item['guid'] = $activity['uuid'];
1173                 $item['title'] = HTML::toBBCode($activity['name']);
1174                 $item['content-warning'] = HTML::toBBCode($activity['summary']);
1175                 $item['body'] = self::convertMentions(HTML::toBBCode($activity['content']));
1176                 $item['location'] = $activity['location'];
1177                 $item['tag'] = self::constructTagList($activity['tags'], $activity['sensitive']);
1178                 $item['app'] = $activity['service'];
1179                 $item['plink'] = defaults($activity, 'alternate-url', $item['uri']);
1180
1181                 $item = self::constructAttachList($activity['attachments'], $item);
1182
1183                 $source = JsonLD::fetchElement($activity, 'source', 'content', 'mediaType', 'text/bbcode');
1184                 if (!empty($source)) {
1185                         $item['body'] = $source;
1186                 }
1187
1188                 $item['protocol'] = Conversation::PARCEL_ACTIVITYPUB;
1189                 $item['source'] = $body;
1190                 $item['conversation-uri'] = $activity['conversation'];
1191
1192                 foreach ($activity['receiver'] as $receiver) {
1193                         $item['uid'] = $receiver;
1194                         $item['contact-id'] = Contact::getIdForURL($activity['author'], $receiver, true);
1195
1196                         if (($receiver != 0) && empty($item['contact-id'])) {
1197                                 $item['contact-id'] = Contact::getIdForURL($activity['author'], 0, true);
1198                         }
1199
1200                         $item_id = Item::insert($item);
1201                         logger('Storing for user ' . $item['uid'] . ': ' . $item_id);
1202                 }
1203         }
1204
1205         private static function fetchMissingActivity($url, $child)
1206         {
1207                 $object = ActivityPub::fetchContent($url);
1208                 if (empty($object)) {
1209                         logger('Activity ' . $url . ' was not fetchable, aborting.');
1210                         return;
1211                 }
1212
1213                 $activity = [];
1214                 $activity['@context'] = $object['@context'];
1215                 unset($object['@context']);
1216                 $activity['id'] = $object['id'];
1217                 $activity['to'] = defaults($object, 'to', []);
1218                 $activity['cc'] = defaults($object, 'cc', []);
1219                 $activity['actor'] = $child['author'];
1220                 $activity['object'] = $object;
1221                 $activity['published'] = $object['published'];
1222                 $activity['type'] = 'Create';
1223
1224                 self::processActivity($activity);
1225                 logger('Activity ' . $url . ' had been fetched and processed.');
1226         }
1227
1228         private static function getUserOfObject($object)
1229         {
1230                 $self = DBA::selectFirst('contact', ['uid'], ['nurl' => normalise_link($object), 'self' => true]);
1231                 if (!DBA::isResult($self)) {
1232                         return false;
1233                 } else {
1234                         return $self['uid'];
1235                 }
1236         }
1237
1238         private static function followUser($activity)
1239         {
1240                 $uid = self::getUserOfObject($activity['object']);
1241                 if (empty($uid)) {
1242                         return;
1243                 }
1244
1245                 $owner = User::getOwnerDataById($uid);
1246
1247                 $cid = Contact::getIdForURL($activity['owner'], $uid);
1248                 if (!empty($cid)) {
1249                         $contact = DBA::selectFirst('contact', [], ['id' => $cid]);
1250                 } else {
1251                         $contact = false;
1252                 }
1253
1254                 $item = ['author-id' => Contact::getIdForURL($activity['owner']),
1255                         'author-link' => $activity['owner']];
1256
1257                 Contact::addRelationship($owner, $contact, $item);
1258                 $cid = Contact::getIdForURL($activity['owner'], $uid);
1259                 if (empty($cid)) {
1260                         return;
1261                 }
1262
1263                 $contact = DBA::selectFirst('contact', ['network'], ['id' => $cid]);
1264                 if ($contact['network'] != Protocol::ACTIVITYPUB) {
1265                         Contact::updateFromProbe($cid, Protocol::ACTIVITYPUB);
1266                 }
1267
1268                 DBA::update('contact', ['hub-verify' => $activity['id']], ['id' => $cid]);
1269                 logger('Follow user ' . $uid . ' from contact ' . $cid . ' with id ' . $activity['id']);
1270         }
1271
1272         private static function acceptFollowUser($activity)
1273         {
1274                 $uid = self::getUserOfObject($activity['object']);
1275                 if (empty($uid)) {
1276                         return;
1277                 }
1278
1279                 $owner = User::getOwnerDataById($uid);
1280
1281                 $cid = Contact::getIdForURL($activity['owner'], $uid);
1282                 if (empty($cid)) {
1283                         logger('No contact found for ' . $activity['owner'], LOGGER_DEBUG);
1284                         return;
1285                 }
1286
1287                 $fields = ['pending' => false];
1288
1289                 $contact = DBA::selectFirst('contact', ['rel'], ['id' => $cid]);
1290                 if ($contact['rel'] == Contact::FOLLOWER) {
1291                         $fields['rel'] = Contact::FRIEND;
1292                 }
1293
1294                 $condition = ['id' => $cid];
1295                 DBA::update('contact', $fields, $condition);
1296                 logger('Accept contact request from contact ' . $cid . ' for user ' . $uid, LOGGER_DEBUG);
1297         }
1298
1299         private static function undoFollowUser($activity)
1300         {
1301                 $uid = self::getUserOfObject($activity['object']);
1302                 if (empty($uid)) {
1303                         return;
1304                 }
1305
1306                 $owner = User::getOwnerDataById($uid);
1307
1308                 $cid = Contact::getIdForURL($activity['owner'], $uid);
1309                 if (empty($cid)) {
1310                         logger('No contact found for ' . $activity['owner'], LOGGER_DEBUG);
1311                         return;
1312                 }
1313
1314                 $contact = DBA::selectFirst('contact', [], ['id' => $cid]);
1315                 if (!DBA::isResult($contact)) {
1316                         return;
1317                 }
1318
1319                 Contact::removeFollower($owner, $contact);
1320                 logger('Undo following request from contact ' . $cid . ' for user ' . $uid, LOGGER_DEBUG);
1321         }
1322 }