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