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