]> git.mxchange.org Git - friendica.git/blob - src/Protocol/ActivityPub.php
Merge remote-tracking branch 'upstream/2018.08-rc' into ap1
[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\User;
17 use Friendica\Util\DateTimeFormat;
18 use Friendica\Util\Crypto;
19 use Friendica\Content\Text\BBCode;
20 use Friendica\Content\Text\HTML;
21 use Friendica\Network\Probe;
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  *
36  * Part of the code for HTTP signing is taken from the Osada project.
37  * 
38  *
39  * To-do:
40  *
41  * Receiver:
42  * - Activities: Dislike, Update, Delete
43  * - Object Types: Person, Tombstome
44  *
45  * Transmitter:
46  * - Activities: Like, Dislike, Update, Delete
47  * - Object Tyoes: Article, Announce, Person, Tombstone
48  *
49  * General:
50  * - Message distribution
51  * - Endpoints: Outbox, Object, Follower, Following
52  */
53 class ActivityPub
54 {
55         const PUBLIC = 'https://www.w3.org/ns/activitystreams#Public';
56
57         public static function transmit($data, $target, $uid)
58         {
59                 $owner = User::getOwnerDataById($uid);
60
61                 if (!$owner) {
62                         return;
63                 }
64
65                 $content = json_encode($data);
66
67                 $host = parse_url($target, PHP_URL_HOST);
68                 $path = parse_url($target, PHP_URL_PATH);
69                 $date = date('r');
70
71                 $headers = ['Host: ' . $host, 'Date: ' . $date];
72
73                 $signed_data = "(request-target): post " . $path . "\nhost: " . $host . "\ndate: " . $date;
74
75                 $signature = base64_encode(Crypto::rsaSign($signed_data, $owner['uprvkey'], 'sha256'));
76
77                 $headers[] = 'Signature: keyId="' . $owner['url'] . '#main-key' . '",headers="(request-target) host date",signature="' . $signature . '"';
78                 $headers[] = 'Content-Type: application/activity+json';
79
80                 Network::post($target, $content, $headers);
81                 $return_code = BaseObject::getApp()->get_curl_code();
82
83                 logger('Transmit to ' . $target . ' returned ' . $return_code);
84         }
85
86         /**
87          * Return the ActivityPub profile of the given user
88          *
89          * @param integer $uid User ID
90          * @return array
91          */
92         public static function profile($uid)
93         {
94                 $accounttype = ['Person', 'Organization', 'Service', 'Group', 'Application'];
95
96                 $condition = ['uid' => $uid, 'blocked' => false, 'account_expired' => false,
97                         'account_removed' => false, 'verified' => true];
98                 $fields = ['guid', 'nickname', 'pubkey', 'account-type'];
99                 $user = DBA::selectFirst('user', $fields, $condition);
100                 if (!DBA::isResult($user)) {
101                         return [];
102                 }
103
104                 $fields = ['locality', 'region', 'country-name'];
105                 $profile = DBA::selectFirst('profile', $fields, ['uid' => $uid, 'is-default' => true]);
106                 if (!DBA::isResult($profile)) {
107                         return [];
108                 }
109
110                 $fields = ['name', 'url', 'location', 'about', 'avatar'];
111                 $contact = DBA::selectFirst('contact', $fields, ['uid' => $uid, 'self' => true]);
112                 if (!DBA::isResult($contact)) {
113                         return [];
114                 }
115
116                 $data = ['@context' => ['https://www.w3.org/ns/activitystreams', 'https://w3id.org/security/v1',
117                         ['uuid' => 'http://schema.org/identifier', 'sensitive' => 'as:sensitive',
118                         'vcard' => 'http://www.w3.org/2006/vcard/ns#']]];
119
120                 $data['id'] = $contact['url'];
121                 $data['uuid'] = $user['guid'];
122                 $data['type'] = $accounttype[$user['account-type']];
123                 $data['following'] = System::baseUrl() . '/following/' . $user['nickname'];
124                 $data['followers'] = System::baseUrl() . '/followers/' . $user['nickname'];
125                 $data['inbox'] = System::baseUrl() . '/inbox/' . $user['nickname'];
126                 $data['outbox'] = System::baseUrl() . '/outbox/' . $user['nickname'];
127                 $data['preferredUsername'] = $user['nickname'];
128                 $data['name'] = $contact['name'];
129                 $data['vcard:hasAddress'] = ['@type' => 'Home', 'vcard:country-name' => $profile['country-name'],
130                         'vcard:region' => $profile['region'], 'vcard:locality' => $profile['locality']];
131                 $data['summary'] = $contact['about'];
132                 $data['url'] = $contact['url'];
133                 $data['manuallyApprovesFollowers'] = false;
134                 $data['publicKey'] = ['id' => $contact['url'] . '#main-key',
135                         'owner' => $contact['url'],
136                         'publicKeyPem' => $user['pubkey']];
137                 $data['endpoints'] = ['sharedInbox' => System::baseUrl() . '/inbox'];
138                 $data['icon'] = ['type' => 'Image',
139                         'url' => $contact['avatar']];
140
141                 // tags: https://kitty.town/@inmysocks/100656097926961126.json
142                 return $data;
143         }
144
145         public static function createActivityFromItem($item_id)
146         {
147                 $item = Item::selectFirst([], ['id' => $item_id]);
148
149                 $data = ['@context' => ['https://www.w3.org/ns/activitystreams', 'https://w3id.org/security/v1',
150                         ['Emoji' => 'toot:Emoji', 'Hashtag' => 'as:Hashtag', 'atomUri' => 'ostatus:atomUri',
151                         'conversation' => 'ostatus:conversation', 'inReplyToAtomUri' => 'ostatus:inReplyToAtomUri',
152                         'ostatus' => 'http://ostatus.org#', 'sensitive' => 'as:sensitive',
153                         'toot' => 'http://joinmastodon.org/ns#']]];
154
155                 $data['type'] = 'Create';
156                 $data['id'] = $item['uri'];
157                 $data['actor'] = $item['author-link'];
158                 $data['to'] = 'https://www.w3.org/ns/activitystreams#Public';
159                 $data['object'] = self::createNote($item);
160                 return $data;
161         }
162
163         public static function createNote($item)
164         {
165                 $data = [];
166                 $data['type'] = 'Note';
167                 $data['id'] = $item['uri'];
168
169                 if ($item['uri'] != $item['thr-parent']) {
170                         $data['inReplyTo'] = $item['thr-parent'];
171                 }
172
173                 $conversation = DBA::selectFirst('conversation', ['conversation-uri'], ['item-uri' => $item['parent-uri']]);
174                 if (DBA::isResult($conversation) && !empty($conversation['conversation-uri'])) {
175                         $conversation_uri = $conversation['conversation-uri'];
176                 } else {
177                         $conversation_uri = $item['parent-uri'];
178                 }
179
180                 $data['context'] = $data['conversation'] = $conversation_uri;
181                 $data['actor'] = $item['author-link'];
182                 $data['to'] = [];
183                 if (!$item['private']) {
184                         $data['to'][] = 'https://www.w3.org/ns/activitystreams#Public';
185                 }
186                 $data['published'] = DateTimeFormat::utc($item["created"]."+00:00", DateTimeFormat::ATOM);
187                 $data['updated'] = DateTimeFormat::utc($item["edited"]."+00:00", DateTimeFormat::ATOM);
188                 $data['attributedTo'] = $item['author-link'];
189                 $data['name'] = BBCode::convert($item['title'], false, 7);
190                 $data['content'] = BBCode::convert($item['body'], false, 7);
191                 $data['source'] = ['content' => $item['body'], 'mediaType' => "text/bbcode"];
192                 //$data['summary'] = ''; // Ignore by now
193                 //$data['sensitive'] = false; // - Query NSFW
194                 //$data['emoji'] = []; // Ignore by now
195                 //$data['tag'] = []; /// @ToDo
196                 //$data['attachment'] = []; // @ToDo
197                 return $data;
198         }
199
200         public static function transmitActivity($activity, $target, $uid)
201         {
202                 $profile = Probe::uri($target, Protocol::ACTIVITYPUB);
203
204                 $owner = User::getOwnerDataById($uid);
205
206                 $data = ['@context' => 'https://www.w3.org/ns/activitystreams',
207                         'id' => System::baseUrl() . '/activity/' . System::createGUID(),
208                         'type' => $activity,
209                         'actor' => $owner['url'],
210                         'object' => $profile['url']];
211
212                 logger('Sending activity ' . $activity . ' to ' . $target . ' for user ' . $uid, LOGGER_DEBUG);
213                 return self::transmit($data,  $profile['notify'], $uid);
214         }
215
216         public static function transmitContactAccept($target, $id, $uid)
217         {
218                 $profile = Probe::uri($target, Protocol::ACTIVITYPUB);
219
220                 $owner = User::getOwnerDataById($uid);
221                 $data = ['@context' => 'https://www.w3.org/ns/activitystreams',
222                         'id' => System::baseUrl() . '/activity/' . System::createGUID(),
223                         'type' => 'Accept',
224                         'actor' => $owner['url'],
225                         'object' => ['id' => $id, 'type' => 'Follow',
226                                 'actor' => $profile['url'],
227                                 'object' => $owner['url']]];
228
229                 logger('Sending accept to ' . $target . ' for user ' . $uid . ' with id ' . $id, LOGGER_DEBUG);
230                 return self::transmit($data,  $profile['notify'], $uid);
231         }
232
233         public static function transmitContactUndo($target, $id, $uid)
234         {
235                 $profile = Probe::uri($target, Protocol::ACTIVITYPUB);
236
237                 if (empty($id)) {
238                         $id = System::baseUrl() . '/activity/' . System::createGUID();
239                 }
240
241                 $owner = User::getOwnerDataById($uid);
242                 $data = ['@context' => 'https://www.w3.org/ns/activitystreams',
243                         'id' => System::baseUrl() . '/activity/' . System::createGUID(),
244                         'type' => 'Undo',
245                         'actor' => $owner['url'],
246                         'object' => ['id' => $id, 'type' => 'Follow',
247                                 'actor' => $owner['url'],
248                                 'object' => $profile['url']]];
249
250                 logger('Sending undo to ' . $target . ' for user ' . $uid . ' with id ' . $id, LOGGER_DEBUG);
251                 return self::transmit($data,  $profile['notify'], $uid);
252         }
253
254         /**
255          * Fetches ActivityPub content from the given url
256          *
257          * @param string $url content url
258          * @return array
259          */
260         public static function fetchContent($url)
261         {
262                 $ret = Network::curl($url, false, $redirects, ['accept_content' => 'application/activity+json']);
263
264                 if (!$ret['success'] || empty($ret['body'])) {
265                         return;
266                 }
267
268                 return json_decode($ret['body'], true);
269         }
270
271         /**
272          * Resolves the profile url from the address by using webfinger
273          *
274          * @param string $addr profile address (user@domain.tld)
275          * @return string url
276          */
277         private static function addrToUrl($addr)
278         {
279                 $addr_parts = explode('@', $addr);
280                 if (count($addr_parts) != 2) {
281                         return false;
282                 }
283
284                 $webfinger = 'https://' . $addr_parts[1] . '/.well-known/webfinger?resource=acct:' . urlencode($addr);
285
286                 $ret = Network::curl($webfinger, false, $redirects, ['accept_content' => 'application/jrd+json,application/json']);
287                 if (!$ret['success'] || empty($ret['body'])) {
288                         return false;
289                 }
290
291                 $data = json_decode($ret['body'], true);
292
293                 if (empty($data['links'])) {
294                         return false;
295                 }
296
297                 foreach ($data['links'] as $link) {
298                         if (empty($link['href']) || empty($link['rel']) || empty($link['type'])) {
299                                 continue;
300                         }
301
302                         if (($link['rel'] == 'self') && ($link['type'] == 'application/activity+json')) {
303                                 return $link['href'];
304                         }
305                 }
306
307                 return false;
308         }
309
310         public static function verifySignature($content, $http_headers)
311         {
312                 $object = json_decode($content, true);
313
314                 if (empty($object)) {
315                         return false;
316                 }
317
318                 $actor = self::processElement($object, 'actor', 'id');
319
320                 $headers = [];
321                 $headers['(request-target)'] = strtolower($http_headers['REQUEST_METHOD']) . ' ' . $http_headers['REQUEST_URI'];
322
323                 // First take every header
324                 foreach ($http_headers as $k => $v) {
325                         $field = str_replace('_', '-', strtolower($k));
326                         $headers[$field] = $v;
327                 }
328
329                 // Now add every http header
330                 foreach ($http_headers as $k => $v) {
331                         if (strpos($k, 'HTTP_') === 0) {
332                                 $field = str_replace('_', '-', strtolower(substr($k, 5)));
333                                 $headers[$field] = $v;
334                         }
335                 }
336
337                 $sig_block = ActivityPub::parseSigHeader($http_headers['HTTP_SIGNATURE']);
338
339                 if (empty($sig_block) || empty($sig_block['headers']) || empty($sig_block['keyId'])) {
340                         return false;
341                 }
342
343                 $signed_data = '';
344                 foreach ($sig_block['headers'] as $h) {
345                         if (array_key_exists($h, $headers)) {
346                                 $signed_data .= $h . ': ' . $headers[$h] . "\n";
347                         }
348                 }
349                 $signed_data = rtrim($signed_data, "\n");
350
351                 if (empty($signed_data)) {
352                         return false;
353                 }
354
355                 $algorithm = null;
356
357                 if ($sig_block['algorithm'] === 'rsa-sha256') {
358                         $algorithm = 'sha256';
359                 }
360
361                 if ($sig_block['algorithm'] === 'rsa-sha512') {
362                         $algorithm = 'sha512';
363                 }
364
365                 if (empty($algorithm)) {
366                         return false;
367                 }
368
369                 $key = self::fetchKey($sig_block['keyId'], $actor);
370
371                 if (empty($key)) {
372                         return false;
373                 }
374
375                 if (!Crypto::rsaVerify($signed_data, $sig_block['signature'], $key, $algorithm)) {
376                         return false;
377                 }
378
379                 // Check the digest if it was part of the signed data
380                 if (in_array('digest', $sig_block['headers'])) {
381                         $digest = explode('=', $headers['digest'], 2);
382                         if ($digest[0] === 'SHA-256') {
383                                 $hashalg = 'sha256';
384                         }
385                         if ($digest[0] === 'SHA-512') {
386                                 $hashalg = 'sha512';
387                         }
388
389                         /// @todo add all hashes from the rfc
390
391                         if (!empty($hashalg) && base64_encode(hash($hashalg, $content, true)) != $digest[1]) {
392                                 return false;
393                         }
394                 }
395
396                 // Check the content-length if it was part of the signed data
397                 if (in_array('content-length', $sig_block['headers'])) {
398                         if (strlen($content) != $headers['content-length']) {
399                                 return false;
400                         }
401                 }
402
403                 return true;
404
405         }
406
407         private static function fetchKey($id, $actor)
408         {
409                 $url = (strpos($id, '#') ? substr($id, 0, strpos($id, '#')) : $id);
410
411                 $profile = Probe::uri($url, Protocol::ACTIVITYPUB);
412                 if (!empty($profile)) {
413                         return $profile['pubkey'];
414                 } elseif ($url != $actor) {
415                         $profile = Probe::uri($actor, Protocol::ACTIVITYPUB);
416                         if (!empty($profile)) {
417                                 return $profile['pubkey'];
418                         }
419                 }
420
421                 return false;
422         }
423
424         /**
425          * @brief
426          *
427          * @param string $header
428          * @return array associate array with
429          *   - \e string \b keyID
430          *   - \e string \b algorithm
431          *   - \e array  \b headers
432          *   - \e string \b signature
433          */
434         private static function parseSigHeader($header)
435         {
436                 $ret = [];
437                 $matches = [];
438
439                 if (preg_match('/keyId="(.*?)"/ism',$header,$matches)) {
440                         $ret['keyId'] = $matches[1];
441                 }
442
443                 if (preg_match('/algorithm="(.*?)"/ism',$header,$matches)) {
444                         $ret['algorithm'] = $matches[1];
445                 }
446
447                 if (preg_match('/headers="(.*?)"/ism',$header,$matches)) {
448                         $ret['headers'] = explode(' ', $matches[1]);
449                 }
450
451                 if (preg_match('/signature="(.*?)"/ism',$header,$matches)) {
452                         $ret['signature'] = base64_decode(preg_replace('/\s+/','',$matches[1]));
453                 }
454
455                 return $ret;
456         }
457
458         /**
459          * Fetches a profile from the given url
460          *
461          * @param string $url profile url
462          * @return array
463          */
464         public static function fetchProfile($url)
465         {
466                 if (empty(parse_url($url, PHP_URL_SCHEME))) {
467                         $url = self::addrToUrl($url);
468                         if (empty($url)) {
469                                 return false;
470                         }
471                 }
472
473                 $data = self::fetchContent($url);
474
475                 if (empty($data) || empty($data['id']) || empty($data['inbox'])) {
476                         return false;
477                 }
478
479                 $profile = ['network' => Protocol::ACTIVITYPUB];
480                 $profile['nick'] = $data['preferredUsername'];
481                 $profile['name'] = defaults($data, 'name', $profile['nick']);
482                 $profile['guid'] = defaults($data, 'uuid', null);
483                 $profile['url'] = $data['id'];
484
485                 $parts = parse_url($profile['url']);
486                 unset($parts['scheme']);
487                 unset($parts['path']);
488                 $profile['addr'] = $profile['nick'] . '@' . str_replace('//', '', Network::unparseURL($parts));
489                 $profile['alias'] = self::processElement($data, 'url', 'href');
490                 $profile['photo'] = self::processElement($data, 'icon', 'url');
491                 // $profile['community']
492                 // $profile['keywords']
493                 // $profile['location']
494                 $profile['about'] = defaults($data, 'summary', '');
495                 $profile['batch'] = self::processElement($data, 'endpoints', 'sharedInbox');
496                 $profile['notify'] = $data['inbox'];
497                 $profile['poll'] = $data['outbox'];
498                 $profile['pubkey'] = self::processElement($data, 'publicKey', 'publicKeyPem');
499
500                 // Check if the address is resolvable
501                 if (self::addrToUrl($profile['addr']) == $profile['url']) {
502                         $parts = parse_url($profile['url']);
503                         unset($parts['path']);
504                         $profile['baseurl'] = Network::unparseURL($parts);
505                 } else {
506                         unset($profile['addr']);
507                 }
508
509                 if ($profile['url'] == $profile['alias']) {
510                         unset($profile['alias']);
511                 }
512
513                 // Remove all "null" fields
514                 foreach ($profile as $field => $content) {
515                         if (is_null($content)) {
516                                 unset($profile[$field]);
517                         }
518                 }
519
520 /*
521                 // To-Do
522                 unset($data['type']);
523                 unset($data['manuallyApprovesFollowers']);
524
525                 // Unhandled
526                 unset($data['@context']);
527                 unset($data['tag']);
528                 unset($data['attachment']);
529                 unset($data['image']);
530                 unset($data['nomadicLocations']);
531                 unset($data['signature']);
532                 unset($data['following']);
533                 unset($data['followers']);
534                 unset($data['featured']);
535                 unset($data['movedTo']);
536                 unset($data['liked']);
537                 unset($data['sharedInbox']); // Misskey
538                 unset($data['isCat']); // Misskey
539                 unset($data['kroeg:blocks']); // Kroeg
540                 unset($data['updated']); // Kroeg
541 */
542                 return $profile;
543         }
544
545         public static function processInbox($body, $header, $uid)
546         {
547                 logger('Incoming message for user ' . $uid, LOGGER_DEBUG);
548
549                 if (!self::verifySignature($body, $header)) {
550                         logger('Invalid signature, message will be discarded.', LOGGER_DEBUG);
551                         return;
552                 }
553
554                 $activity = json_decode($body, true);
555
556                 if (!is_array($activity)) {
557                         logger('Invalid body.', LOGGER_DEBUG);
558                         return;
559                 }
560
561                 self::processActivity($activity, $body, $uid);
562         }
563
564         public static function fetchOutbox($url)
565         {
566                 $data = self::fetchContent($url);
567                 if (empty($data)) {
568                         return;
569                 }
570
571                 if (!empty($data['orderedItems'])) {
572                         $items = $data['orderedItems'];
573                 } elseif (!empty($data['first']['orderedItems'])) {
574                         $items = $data['first']['orderedItems'];
575                 } elseif (!empty($data['first'])) {
576                         self::fetchOutbox($data['first']);
577                         return;
578                 } else {
579                         $items = [];
580                 }
581
582                 foreach ($items as $activity) {
583                         self::processActivity($activity);
584                 }
585         }
586
587         function processActivity($activity, $body = '', $uid = null)
588         {
589                 if (empty($activity['type'])) {
590                         logger('Empty type', LOGGER_DEBUG);
591                         return;
592                 }
593
594                 if (empty($activity['object'])) {
595                         logger('Empty object', LOGGER_DEBUG);
596                         return;
597                 }
598
599                 if (empty($activity['actor'])) {
600                         logger('Empty actor', LOGGER_DEBUG);
601                         return;
602
603                 }
604
605                 $actor = self::processElement($activity, 'actor', 'id');
606                 if (empty($actor)) {
607                         logger('Empty actor - 2', LOGGER_DEBUG);
608                         return;
609                 }
610
611                 if (is_string($activity['object'])) {
612                         $object_url = $activity['object'];
613                 } elseif (!empty($activity['object']['id'])) {
614                         $object_url = $activity['object']['id'];
615                 } else {
616                         logger('No object found', LOGGER_DEBUG);
617                         return;
618                 }
619
620                 // ----------------------------------
621 /*
622                 // unhandled
623                 unset($activity['@context']);
624                 unset($activity['id']);
625
626                 // Non standard
627                 unset($activity['title']);
628                 unset($activity['atomUri']);
629                 unset($activity['context_id']);
630                 unset($activity['statusnetConversationId']);
631
632                 // To-Do?
633                 unset($activity['context']);
634                 unset($activity['location']);
635                 unset($activity['signature']);
636 */
637                 // Fetch all receivers from to, cc, bto and bcc
638                 $receivers = self::getReceivers($activity);
639
640                 // When it is a delivery to a personal inbox we add that user to the receivers
641                 if (!empty($uid)) {
642                         $owner = User::getOwnerDataById($uid);
643                         $additional = [$owner['url'] => $uid];
644                         $receivers = array_merge($receivers, $additional);
645                 }
646
647                 logger('Receivers: ' . json_encode($receivers), LOGGER_DEBUG);
648
649                 logger('Processing activity: ' . $activity['type'], LOGGER_DEBUG);
650
651                 // Fetch the content only on activities where this matters
652                 if (in_array($activity['type'], ['Create', 'Update', 'Announce'])) {
653                         $item = self::fetchObject($object_url, $activity['object']);
654                         if (empty($item)) {
655                                 logger("Object data couldn't be processed", LOGGER_DEBUG);
656                                 return;
657                         }
658                 } else {
659                         if (in_array($activity['type'], ['Accept'])) {
660                                 $item['object'] = self::processElement($activity, 'object', 'actor', 'type', 'Follow');
661                         } elseif (in_array($activity['type'], ['Undo'])) {
662                                 $item['object'] = self::processElement($activity, 'object', 'object', 'type', 'Follow');
663                         } else {
664                                 $item['object'] = $object_url;
665                         }
666                         $item['id'] = $activity['id'];
667                         $item['receiver'] = [];
668                         $item['type'] = $activity['type'];
669                 }
670
671                 $item = self::addActivityFields($item, $activity);
672
673                 $item['owner'] = $actor;
674
675                 $item['receiver'] = array_merge($item['receiver'], $receivers);
676
677                 switch ($activity['type']) {
678                         case 'Create':
679                         case 'Update':
680                         case 'Announce':
681                                 self::createItem($item, $body);
682                                 break;
683
684                         case 'Like':
685                                 self::likeItem($item, $body);
686                                 break;
687
688                         case 'Dislike':
689                                 break;
690
691                         case 'Delete':
692                                 break;
693
694                         case 'Follow':
695                                 self::followUser($item);
696                                 break;
697
698                         case 'Accept':
699                                 self::acceptFollowUser($item);
700                                 break;
701
702                         case 'Undo':
703                                 self::undoFollowUser($item);
704                                 break;
705
706                         default:
707                                 logger('Unknown activity: ' . $activity['type'], LOGGER_DEBUG);
708                                 break;
709                 }
710         }
711
712         private static function getReceivers($activity)
713         {
714                 $receivers = [];
715
716                 $elements = ['to', 'cc', 'bto', 'bcc'];
717                 foreach ($elements as $element) {
718                         if (empty($activity[$element])) {
719                                 continue;
720                         }
721
722                         // The receiver can be an arror or a string
723                         if (is_string($activity[$element])) {
724                                 $activity[$element] = [$activity[$element]];
725                         }
726
727                         foreach ($activity[$element] as $receiver) {
728                                 if ($receiver == self::PUBLIC) {
729                                         $receivers[$receiver] = 0;
730                                 }
731
732                                 $condition = ['self' => true, 'nurl' => normalise_link($receiver)];
733                                 $contact = DBA::selectFirst('contact', ['uid'], $condition);
734                                 if (!DBA::isResult($contact)) {
735                                         continue;
736                                 }
737                                 $receivers[$receiver] = $contact['uid'];
738                         }
739                 }
740                 return $receivers;
741         }
742
743         private static function addActivityFields($item, $activity)
744         {
745                 if (!empty($activity['published']) && empty($item['published'])) {
746                         $item['published'] = $activity['published'];
747                 }
748
749                 if (!empty($activity['updated']) && empty($item['updated'])) {
750                         $item['updated'] = $activity['updated'];
751                 }
752
753                 if (!empty($activity['inReplyTo']) && empty($item['parent-uri'])) {
754                         $item['parent-uri'] = self::processElement($activity, 'inReplyTo', 'id');
755                 }
756
757                 if (!empty($activity['instrument'])) {
758                         $item['service'] = self::processElement($activity, 'instrument', 'name', 'type', 'Service');
759                 }
760                 return $item;
761         }
762
763         private static function fetchObject($object_url, $object = [])
764         {
765                 $data = self::fetchContent($object_url);
766                 if (empty($data)) {
767                         $data = $object;
768                         if (empty($data)) {
769                                 logger('Empty content', LOGGER_DEBUG);
770                                 return false;
771                         } elseif (is_string($data)) {
772                                 logger('No object array provided.', LOGGER_DEBUG);
773                                 $item = Item::selectFirst([], ['uri' => $data]);
774                                 if (!DBA::isResult($item)) {
775                                         logger('Object with url ' . $data . ' was not found locally.', LOGGER_DEBUG);
776                                         return false;
777                                 }
778                                 logger('Using already stored item', LOGGER_DEBUG);
779                                 $data = self::createNote($item);
780                         } else {
781                                 logger('Using provided object', LOGGER_DEBUG);
782                         }
783                 }
784
785                 if (empty($data['type'])) {
786                         logger('Empty type', LOGGER_DEBUG);
787                         return false;
788                 } else {
789                         $type = $data['type'];
790                         logger('Type ' . $type, LOGGER_DEBUG);
791                 }
792
793                 if (in_array($type, ['Note', 'Article', 'Video'])) {
794                         $common = self::processCommonData($data);
795                 }
796
797                 switch ($type) {
798                         case 'Note':
799                                 return array_merge($common, self::processNote($data));
800                         case 'Article':
801                                 return array_merge($common, self::processArticle($data));
802                         case 'Video':
803                                 return array_merge($common, self::processVideo($data));
804
805                         case 'Announce':
806                                 if (empty($data['object'])) {
807                                         return false;
808                                 }
809                                 return self::fetchObject($data['object']);
810
811                         case 'Person':
812                         case 'Tombstone':
813                                 break;
814
815                         default:
816                                 logger('Unknown object type: ' . $data['type'], LOGGER_DEBUG);
817                                 break;
818                 }
819         }
820
821         private static function processCommonData(&$object)
822         {
823                 if (empty($object['id']) || empty($object['attributedTo'])) {
824                         return false;
825                 }
826
827                 $item = [];
828                 $item['type'] = $object['type'];
829                 $item['uri'] = $object['id'];
830
831                 if (!empty($object['inReplyTo'])) {
832                         $item['reply-to-uri'] = self::processElement($object, 'inReplyTo', 'id');
833                 } else {
834                         $item['reply-to-uri'] = $item['uri'];
835                 }
836
837                 $item['published'] = defaults($object, 'published', null);
838                 $item['updated'] = defaults($object, 'updated', $item['published']);
839
840                 if (empty($item['published']) && !empty($item['updated'])) {
841                         $item['published'] = $item['updated'];
842                 }
843
844                 $item['uuid'] = defaults($object, 'uuid', null);
845                 $item['owner'] = $item['author'] = self::processElement($object, 'attributedTo', 'id');
846                 $item['context'] = defaults($object, 'context', null);
847                 $item['conversation'] = defaults($object, 'conversation', null);
848                 $item['sensitive'] = defaults($object, 'sensitive', null);
849                 $item['name'] = defaults($object, 'title', null);
850                 $item['name'] = defaults($object, 'name', $item['name']);
851                 $item['summary'] = defaults($object, 'summary', null);
852                 $item['content'] = defaults($object, 'content', null);
853                 $item['source'] = defaults($object, 'source', null);
854                 $item['location'] = self::processElement($object, 'location', 'name', 'type', 'Place');
855                 $item['attachments'] = defaults($object, 'attachment', null);
856                 $item['tags'] = defaults($object, 'tag', null);
857                 $item['service'] = self::processElement($object, 'instrument', 'name', 'type', 'Service');
858                 $item['alternate-url'] = self::processElement($object, 'url', 'href');
859                 $item['receiver'] = self::getReceivers($object);
860
861 /*
862                 // To-Do
863                 unset($object['source']);
864
865                 // Unhandled
866                 unset($object['@context']);
867                 unset($object['type']);
868                 unset($object['actor']);
869                 unset($object['signature']);
870                 unset($object['mediaType']);
871                 unset($object['duration']);
872                 unset($object['replies']);
873                 unset($object['icon']);
874
875                 // Also missing:
876                 audience, preview, endTime, startTime, generator, image
877 */
878                 return $item;
879         }
880
881         private static function processNote($object)
882         {
883                 $item = [];
884
885 /*
886                 // To-Do?
887                 unset($object['emoji']);
888                 unset($object['atomUri']);
889                 unset($object['inReplyToAtomUri']);
890
891                 // Unhandled
892                 unset($object['contentMap']);
893                 unset($object['announcement_count']);
894                 unset($object['announcements']);
895                 unset($object['context_id']);
896                 unset($object['likes']);
897                 unset($object['like_count']);
898                 unset($object['inReplyToStatusId']);
899                 unset($object['shares']);
900                 unset($object['quoteUrl']);
901                 unset($object['statusnetConversationId']);
902 */
903                 return $item;
904         }
905
906         private static function processArticle($object)
907         {
908                 $item = [];
909
910                 return $item;
911         }
912
913         private static function processVideo($object)
914         {
915                 $item = [];
916 /*
917                 // To-Do?
918                 unset($object['category']);
919                 unset($object['licence']);
920                 unset($object['language']);
921                 unset($object['commentsEnabled']);
922
923                 // Unhandled
924                 unset($object['views']);
925                 unset($object['waitTranscoding']);
926                 unset($object['state']);
927                 unset($object['support']);
928                 unset($object['subtitleLanguage']);
929                 unset($object['likes']);
930                 unset($object['dislikes']);
931                 unset($object['shares']);
932                 unset($object['comments']);
933 */
934                 return $item;
935         }
936
937         private static function processElement($array, $element, $key, $type = null, $type_value = null)
938         {
939                 if (empty($array)) {
940                         return false;
941                 }
942
943                 if (empty($array[$element])) {
944                         return false;
945                 }
946
947                 if (is_string($array[$element])) {
948                         return $array[$element];
949                 }
950
951                 if (is_null($type_value)) {
952                         if (!empty($array[$element][$key])) {
953                                 return $array[$element][$key];
954                         }
955
956                         if (!empty($array[$element][0][$key])) {
957                                 return $array[$element][0][$key];
958                         }
959
960                         return false;
961                 }
962
963                 if (!empty($array[$element][$key]) && !empty($array[$element][$type]) && ($array[$element][$type] == $type_value)) {
964                         return $array[$element][$key];
965                 }
966
967                 /// @todo Add array search
968
969                 return false;
970         }
971
972         private static function convertMentions($body)
973         {
974                 $URLSearchString = "^\[\]";
975                 $body = preg_replace("/\[url\=([$URLSearchString]*)\]([#@!])(.*?)\[\/url\]/ism", '$2[url=$1]$3[/url]', $body);
976
977                 return $body;
978         }
979
980         private static function constructTagList($tags, $sensitive)
981         {
982                 if (empty($tags)) {
983                         return '';
984                 }
985
986                 $tag_text = '';
987                 foreach ($tags as $tag) {
988                         if (in_array($tag['type'], ['Mention', 'Hashtag'])) {
989                                 if (!empty($tag_text)) {
990                                         $tag_text .= ',';
991                                 }
992
993                                 $tag_text .= substr($tag['name'], 0, 1) . '[url=' . $tag['href'] . ']' . substr($tag['name'], 1) . '[/url]';
994                         }
995                 }
996
997                 /// @todo add nsfw for $sensitive
998
999                 return $tag_text;
1000         }
1001
1002         private static function constructAttachList($attachments, $item)
1003         {
1004                 if (empty($attachments)) {
1005                         return $item;
1006                 }
1007
1008                 foreach ($attachments as $attach) {
1009                         $filetype = strtolower(substr($attach['mediaType'], 0, strpos($attach['mediaType'], '/')));
1010                         if ($filetype == 'image') {
1011                                 $item['body'] .= "\n[img]".$attach['url'].'[/img]';
1012                         } else {
1013                                 if (!empty($item["attach"])) {
1014                                         $item["attach"] .= ',';
1015                                 } else {
1016                                         $item["attach"] = '';
1017                                 }
1018                                 if (!isset($attach['length'])) {
1019                                         $attach['length'] = "0";
1020                                 }
1021                                 $item["attach"] .= '[attach]href="'.$attach['url'].'" length="'.$attach['length'].'" type="'.$attach['mediaType'].'" title="'.defaults($attach, 'name', '').'"[/attach]';
1022                         }
1023                 }
1024
1025                 return $item;
1026         }
1027
1028         private static function createItem($activity, $body)
1029         {
1030                 $item = [];
1031                 $item['verb'] = ACTIVITY_POST;
1032                 $item['parent-uri'] = $activity['reply-to-uri'];
1033
1034                 if ($activity['reply-to-uri'] == $activity['uri']) {
1035                         $item['gravity'] = GRAVITY_PARENT;
1036                         $item['object-type'] = ACTIVITY_OBJ_NOTE;
1037                 } else {
1038                         $item['gravity'] = GRAVITY_COMMENT;
1039                         $item['object-type'] = ACTIVITY_OBJ_COMMENT;
1040                 }
1041
1042                 self::postItem($activity, $item, $body);
1043         }
1044
1045         private static function likeItem($activity, $body)
1046         {
1047                 $item = [];
1048                 $item['verb'] = ACTIVITY_LIKE;
1049                 $item['parent-uri'] = $activity['object'];
1050                 $item['gravity'] = GRAVITY_ACTIVITY;
1051                 $item['object-type'] = ACTIVITY_OBJ_NOTE;
1052
1053                 self::postItem($activity, $item, $body);
1054         }
1055
1056         private static function postItem($activity, $item, $body)
1057         {
1058                 /// @todo What to do with $activity['context']?
1059
1060                 $item['network'] = Protocol::ACTIVITYPUB;
1061                 $item['private'] = !in_array(0, $activity['receiver']);
1062                 $item['author-id'] = Contact::getIdForURL($activity['author'], 0, true);
1063                 $item['owner-id'] = Contact::getIdForURL($activity['owner'], 0, true);
1064                 $item['uri'] = $activity['uri'];
1065                 $item['created'] = $activity['published'];
1066                 $item['edited'] = $activity['updated'];
1067                 $item['guid'] = $activity['uuid'];
1068                 $item['title'] = HTML::toBBCode($activity['name']);
1069                 $item['content-warning'] = HTML::toBBCode($activity['summary']);
1070                 $item['body'] = self::convertMentions(HTML::toBBCode($activity['content']));
1071                 $item['location'] = $activity['location'];
1072                 $item['tag'] = self::constructTagList($activity['tags'], $activity['sensitive']);
1073                 $item['app'] = $activity['service'];
1074                 $item['plink'] = defaults($activity, 'alternate-url', $item['uri']);
1075
1076                 $item = self::constructAttachList($activity['attachments'], $item);
1077
1078                 $source = self::processElement($activity, 'source', 'content', 'mediaType', 'text/bbcode');
1079                 if (!empty($source)) {
1080                         $item['body'] = $source;
1081                 }
1082
1083                 $item['protocol'] = Conversation::PARCEL_ACTIVITYPUB;
1084                 $item['source'] = $body;
1085                 $item['conversation-uri'] = $activity['conversation'];
1086
1087                 foreach ($activity['receiver'] as $receiver) {
1088                         $item['uid'] = $receiver;
1089                         $item['contact-id'] = Contact::getIdForURL($activity['author'], $receiver, true);
1090
1091                         if (($receiver != 0) && empty($item['contact-id'])) {
1092                                 $item['contact-id'] = Contact::getIdForURL($activity['author'], 0, true);
1093                         }
1094
1095                         $item_id = Item::insert($item);
1096                         logger('Storing for user ' . $item['uid'] . ': ' . $item_id);
1097                         if (!empty($item_id) && ($item['uid'] == 0)) {
1098                                 Item::distribute($item_id);
1099                         }
1100                 }
1101         }
1102
1103         private static function followUser($activity)
1104         {
1105                 if (empty($activity['receiver'][$activity['object']])) {
1106                         return;
1107                 }
1108
1109                 $uid = $activity['receiver'][$activity['object']];
1110                 $owner = User::getOwnerDataById($uid);
1111
1112                 $cid = Contact::getIdForURL($activity['owner'], $uid);
1113                 if (!empty($cid)) {
1114                         $contact = DBA::selectFirst('contact', [], ['id' => $cid]);
1115                 } else {
1116                         $contact = false;
1117                 }
1118
1119                 $item = ['author-id' => Contact::getIdForURL($activity['owner']),
1120                         'author-link' => $activity['owner']];
1121
1122                 Contact::addRelationship($owner, $contact, $item);
1123                 $cid = Contact::getIdForURL($activity['owner'], $uid);
1124                 if (empty($cid)) {
1125                         return;
1126                 }
1127
1128                 $contact = DBA::selectFirst('contact', ['network'], ['id' => $cid]);
1129                 if ($contact['network'] != Protocol::ACTIVITYPUB) {
1130                         Contact::updateFromProbe($cid, Protocol::ACTIVITYPUB);
1131                 }
1132
1133                 DBA::update('contact', ['hub-verify' => $activity['id']], ['id' => $cid]);
1134                 logger('Follow user ' . $uid . ' from contact ' . $cid . ' with id ' . $activity['id']);
1135         }
1136
1137         private static function acceptFollowUser($activity)
1138         {
1139                 if (empty($activity['receiver'][$activity['object']])) {
1140                         return;
1141                 }
1142
1143                 $uid = $activity['receiver'][$activity['object']];
1144                 $owner = User::getOwnerDataById($uid);
1145
1146                 $cid = Contact::getIdForURL($activity['owner'], $uid);
1147                 if (empty($cid)) {
1148                         logger('No contact found for ' . $activity['owner'], LOGGER_DEBUG);
1149                         return;
1150                 }
1151
1152                 $fields = ['pending' => false];
1153                 $condition = ['id' => $cid, 'pending' => true];
1154                 DBA::update('comtact', $fields, $condition);
1155                 logger('Accept contact request from contact ' . $cid . ' for user ' . $uid, LOGGER_DEBUG);
1156         }
1157
1158         private static function undoFollowUser($activity)
1159         {
1160                 if (empty($activity['receiver'][$activity['object']])) {
1161                         return;
1162                 }
1163
1164                 $uid = $activity['receiver'][$activity['object']];
1165                 $owner = User::getOwnerDataById($uid);
1166
1167                 $cid = Contact::getIdForURL($activity['owner'], $uid);
1168                 if (empty($cid)) {
1169                         logger('No contact found for ' . $activity['owner'], LOGGER_DEBUG);
1170                         return;
1171                 }
1172
1173                 $contact = DBA::selectFirst('contact', [], ['id' => $cid]);
1174                 if (!DBA::isResult($contact)) {
1175                         return;
1176                 }
1177
1178                 Contact::removeFollower($owner, $contact);
1179                 logger('Undo following request from contact ' . $cid . ' for user ' . $uid, LOGGER_DEBUG);
1180         }
1181 }