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