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