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