3 * @file src/Protocol/ActivityPub.php
5 namespace Friendica\Protocol;
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\Item;
14 use Friendica\Model\User;
15 use Friendica\Util\DateTimeFormat;
16 use Friendica\Util\Crypto;
17 use Friendica\Content\Text\BBCode;
20 * @brief ActivityPub Protocol class
21 * The ActivityPub Protocol is a message exchange protocol defined by the W3C.
22 * https://www.w3.org/TR/activitypub/
23 * https://www.w3.org/TR/activitystreams-core/
24 * https://www.w3.org/TR/activitystreams-vocabulary/
26 * https://blog.joinmastodon.org/2018/06/how-to-implement-a-basic-activitypub-server/
27 * https://blog.joinmastodon.org/2018/07/how-to-make-friends-and-verify-requests/
29 * Digest: https://tools.ietf.org/html/rfc5843
30 * https://tools.ietf.org/html/draft-cavage-http-signatures-10#ref-15
34 const PUBLIC = 'https://www.w3.org/ns/activitystreams#Public';
36 public static function transmit($content, $target, $uid)
38 $owner = User::getOwnerDataById($uid);
44 $host = parse_url($target, PHP_URL_HOST);
45 $path = parse_url($target, PHP_URL_PATH);
48 $headers = ['Host: ' . $host, 'Date: ' . $date];
50 $signed_data = "(request-target): post " . $path . "\nhost: " . $host . "\ndate: " . $date;
52 $signature = base64_encode(Crypto::rsaSign($signed_data, $owner['uprvkey'], 'sha256'));
54 $headers[] = 'Signature: keyId="' . $owner['url'] . '#main-key' . '",headers="(request-target) host date",signature="' . $signature . '"';
55 $headers[] = 'Content-Type: application/activity+json';
57 Network::post($target, $content, $headers);
58 $return_code = BaseObject::getApp()->get_curl_code();
60 echo $return_code."\n";
64 * Return the ActivityPub profile of the given user
66 * @param integer $uid User ID
69 public static function profile($uid)
71 $accounttype = ['Person', 'Organization', 'Service', 'Group', 'Application'];
73 $condition = ['uid' => $uid, 'blocked' => false, 'account_expired' => false,
74 'account_removed' => false, 'verified' => true];
75 $fields = ['guid', 'nickname', 'pubkey', 'account-type'];
76 $user = DBA::selectFirst('user', $fields, $condition);
77 if (!DBA::isResult($user)) {
81 $fields = ['locality', 'region', 'country-name'];
82 $profile = DBA::selectFirst('profile', $fields, ['uid' => $uid, 'is-default' => true]);
83 if (!DBA::isResult($profile)) {
87 $fields = ['name', 'url', 'location', 'about', 'avatar'];
88 $contact = DBA::selectFirst('contact', $fields, ['uid' => $uid, 'self' => true]);
89 if (!DBA::isResult($contact)) {
93 $data = ['@context' => ['https://www.w3.org/ns/activitystreams', 'https://w3id.org/security/v1',
94 ['uuid' => 'http://schema.org/identifier', 'sensitive' => 'as:sensitive',
95 'vcard' => 'http://www.w3.org/2006/vcard/ns#']]];
97 $data['id'] = $contact['url'];
98 $data['uuid'] = $user['guid'];
99 $data['type'] = $accounttype[$user['account-type']];
100 $data['following'] = System::baseUrl() . '/following/' . $user['nickname'];
101 $data['followers'] = System::baseUrl() . '/followers/' . $user['nickname'];
102 $data['inbox'] = System::baseUrl() . '/inbox/' . $user['nickname'];
103 $data['outbox'] = System::baseUrl() . '/outbox/' . $user['nickname'];
104 $data['preferredUsername'] = $user['nickname'];
105 $data['name'] = $contact['name'];
106 $data['vcard:hasAddress'] = ['@type' => 'Home', 'vcard:country-name' => $profile['country-name'],
107 'vcard:region' => $profile['region'], 'vcard:locality' => $profile['locality']];
108 $data['summary'] = $contact['about'];
109 $data['url'] = $contact['url'];
110 $data['manuallyApprovesFollowers'] = false;
111 $data['publicKey'] = ['id' => $contact['url'] . '#main-key',
112 'owner' => $contact['url'],
113 'publicKeyPem' => $user['pubkey']];
114 $data['endpoints'] = ['sharedInbox' => System::baseUrl() . '/inbox'];
115 $data['icon'] = ['type' => 'Image',
116 'url' => $contact['avatar']];
118 // tags: https://kitty.town/@inmysocks/100656097926961126.json
122 public static function createActivityFromItem($item_id)
124 $item = Item::selectFirst([], ['id' => $item_id]);
126 $data = ['@context' => ['https://www.w3.org/ns/activitystreams', 'https://w3id.org/security/v1',
127 ['Emoji' => 'toot:Emoji', 'Hashtag' => 'as:Hashtag', 'atomUri' => 'ostatus:atomUri',
128 'conversation' => 'ostatus:conversation', 'inReplyToAtomUri' => 'ostatus:inReplyToAtomUri',
129 'ostatus' => 'http://ostatus.org#', 'sensitive' => 'as:sensitive',
130 'toot' => 'http://joinmastodon.org/ns#']]];
132 $data['type'] = 'Create';
133 $data['id'] = $item['plink'];
134 $data['actor'] = $item['author-link'];
135 $data['to'] = 'https://www.w3.org/ns/activitystreams#Public';
136 $data['object'] = self::createNote($item);
142 public static function createNote($item)
145 $data['type'] = 'Note';
146 $data['id'] = $item['plink'];
147 //$data['context'] = $data['conversation'] = $item['parent-uri'];
148 $data['actor'] = $item['author-link'];
149 // if (!$item['private']) {
151 // $data['to'][] = '"https://pleroma.soykaf.com/users/heluecht"';
152 $data['to'] = 'https://www.w3.org/ns/activitystreams#Public';
153 // $data['cc'] = 'https://pleroma.soykaf.com/users/heluecht';
155 $data['published'] = DateTimeFormat::utc($item["created"]."+00:00", DateTimeFormat::ATOM);
156 $data['updated'] = DateTimeFormat::utc($item["edited"]."+00:00", DateTimeFormat::ATOM);
157 $data['attributedTo'] = $item['author-link'];
158 $data['name'] = BBCode::convert($item['title'], false, 7);
159 $data['content'] = BBCode::convert($item['body'], false, 7);
160 //$data['summary'] = '';
161 //$data['sensitive'] = false;
162 //$data['emoji'] = [];
164 //$data['attachment'] = [];
169 * Fetches ActivityPub content from the given url
171 * @param string $url content url
174 public static function fetchContent($url)
176 $ret = Network::curl($url, false, $redirects, ['accept_content' => 'application/activity+json']);
178 if (!$ret['success'] || empty($ret['body'])) {
182 return json_decode($ret['body'], true);
186 * Resolves the profile url from the address by using webfinger
188 * @param string $addr profile address (user@domain.tld)
191 private static function addrToUrl($addr)
193 $addr_parts = explode('@', $addr);
194 if (count($addr_parts) != 2) {
198 $webfinger = 'https://' . $addr_parts[1] . '/.well-known/webfinger?resource=acct:' . urlencode($addr);
200 $ret = Network::curl($webfinger, false, $redirects, ['accept_content' => 'application/jrd+json,application/json']);
201 if (!$ret['success'] || empty($ret['body'])) {
205 $data = json_decode($ret['body'], true);
207 if (empty($data['links'])) {
211 foreach ($data['links'] as $link) {
212 if (empty($link['href']) || empty($link['rel']) || empty($link['type'])) {
216 if (($link['rel'] == 'self') && ($link['type'] == 'application/activity+json')) {
217 return $link['href'];
224 public static function verifySignature($content, $http_headers)
226 $object = json_decode($content, true);
228 if (empty($object)) {
232 $actor = self::processElement($object, 'actor', 'id');
235 $headers['(request-target)'] = strtolower($http_headers['REQUEST_METHOD']) . ' ' . $http_headers['REQUEST_URI'];
237 // First take every header
238 foreach ($http_headers as $k => $v) {
239 $field = str_replace('_', '-', strtolower($k));
240 $headers[$field] = $v;
243 // Now add every http header
244 foreach ($http_headers as $k => $v) {
245 if (strpos($k, 'HTTP_') === 0) {
246 $field = str_replace('_', '-', strtolower(substr($k, 5)));
247 $headers[$field] = $v;
251 $sig_block = ActivityPub::parseSigHeader($http_headers['HTTP_SIGNATURE']);
253 if (empty($sig_block) || empty($sig_block['headers']) || empty($sig_block['keyId'])) {
258 foreach ($sig_block['headers'] as $h) {
259 if (array_key_exists($h, $headers)) {
260 $signed_data .= $h . ': ' . $headers[$h] . "\n";
263 $signed_data = rtrim($signed_data, "\n");
265 if (empty($signed_data)) {
271 if ($sig_block['algorithm'] === 'rsa-sha256') {
272 $algorithm = 'sha256';
275 if ($sig_block['algorithm'] === 'rsa-sha512') {
276 $algorithm = 'sha512';
279 if (empty($algorithm)) {
283 $key = self::fetchKey($sig_block['keyId'], $actor);
289 if (!Crypto::rsaVerify($signed_data, $sig_block['signature'], $key, $algorithm)) {
293 // Check the digest if it was part of the signed data
294 if (in_array('digest', $sig_block['headers'])) {
295 $digest = explode('=', $headers['digest'], 2);
296 if ($digest[0] === 'SHA-256') {
299 if ($digest[0] === 'SHA-512') {
303 /// @todo addd all hashes from the rfc
305 if (!empty($hashalg) && base64_encode(hash($hashalg, $content, true)) != $digest[1]) {
310 // Check the content-length if it was part of the signed data
311 if (in_array('content-length', $sig_block['headers'])) {
312 if (strlen($content) != $headers['content-length']) {
321 private static function fetchKey($id, $actor)
323 $url = (strpos($id, '#') ? substr($id, 0, strpos($id, '#')) : $id);
325 $profile = self::fetchProfile($url);
326 if (!empty($profile)) {
327 return $profile['pubkey'];
328 } elseif ($url != $actor) {
329 $profile = self::fetchProfile($actor);
330 if (!empty($profile)) {
331 return $profile['pubkey'];
341 * @param string $header
342 * @return array associate array with
343 * - \e string \b keyID
344 * - \e string \b algorithm
345 * - \e array \b headers
346 * - \e string \b signature
348 private static function parseSigHeader($header)
353 if (preg_match('/keyId="(.*?)"/ism',$header,$matches)) {
354 $ret['keyId'] = $matches[1];
357 if (preg_match('/algorithm="(.*?)"/ism',$header,$matches)) {
358 $ret['algorithm'] = $matches[1];
361 if (preg_match('/headers="(.*?)"/ism',$header,$matches)) {
362 $ret['headers'] = explode(' ', $matches[1]);
365 if (preg_match('/signature="(.*?)"/ism',$header,$matches)) {
366 $ret['signature'] = base64_decode(preg_replace('/\s+/','',$matches[1]));
373 * Fetches a profile from the given url
375 * @param string $url profile url
378 public static function fetchProfile($url)
380 if (empty(parse_url($url, PHP_URL_SCHEME))) {
381 $url = self::addrToUrl($url);
387 $data = self::fetchContent($url);
389 if (empty($data) || empty($data['id']) || empty($data['inbox'])) {
393 $profile = ['network' => Protocol::ACTIVITYPUB];
394 $profile['nick'] = $data['preferredUsername'];
395 $profile['name'] = defaults($data, 'name', $profile['nick']);
396 $profile['guid'] = defaults($data, 'uuid', null);
397 $profile['url'] = $data['id'];
398 $profile['alias'] = self::processElement($data, 'url', 'href');
400 $parts = parse_url($profile['url']);
401 unset($parts['scheme']);
402 unset($parts['path']);
403 $profile['addr'] = $profile['nick'] . '@' . str_replace('//', '', Network::unparseURL($parts));
405 $profile['photo'] = self::processElement($data, 'icon', 'url');
406 $profile['about'] = defaults($data, 'summary', '');
407 $profile['batch'] = self::processElement($data, 'endpoints', 'sharedInbox');
408 $profile['pubkey'] = self::processElement($data, 'publicKey', 'publicKeyPem');
409 $profile['notify'] = $data['inbox'];
410 $profile['poll'] = $data['outbox'];
412 // Check if the address is resolvable
413 if (self::addrToUrl($profile['addr']) == $profile['url']) {
414 $parts = parse_url($profile['url']);
415 unset($parts['path']);
416 $profile['baseurl'] = Network::unparseURL($parts);
418 unset($profile['addr']);
421 if ($profile['url'] == $profile['alias']) {
422 unset($profile['alias']);
425 // Remove all "null" fields
426 foreach ($profile as $field => $content) {
427 if (is_null($content)) {
428 unset($profile[$field]);
434 unset($data['inbox']);
435 unset($data['outbox']);
436 unset($data['preferredUsername']);
437 unset($data['name']);
438 unset($data['summary']);
440 unset($data['publicKey']);
441 unset($data['endpoints']);
442 unset($data['icon']);
443 unset($data['uuid']);
446 unset($data['type']);
447 unset($data['manuallyApprovesFollowers']);
450 unset($data['@context']);
452 unset($data['attachment']);
453 unset($data['image']);
454 unset($data['nomadicLocations']);
455 unset($data['signature']);
456 unset($data['following']);
457 unset($data['followers']);
458 unset($data['featured']);
459 unset($data['movedTo']);
460 unset($data['liked']);
461 unset($data['sharedInbox']); // Misskey
462 unset($data['isCat']); // Misskey
463 unset($data['kroeg:blocks']); // Kroeg
464 unset($data['updated']); // Kroeg
466 /* if (!empty($data)) {
474 public static function fetchOutbox($url)
476 $data = self::fetchContent($url);
481 if (!empty($data['orderedItems'])) {
482 $items = $data['orderedItems'];
483 } elseif (!empty($data['first']['orderedItems'])) {
484 $items = $data['first']['orderedItems'];
485 } elseif (!empty($data['first'])) {
486 self::fetchOutbox($data['first']);
492 foreach ($items as $activity) {
493 self::processActivity($activity, $url);
497 function processActivity($activity, $url)
499 if (empty($activity['type'])) {
503 if (empty($activity['object'])) {
507 if (empty($activity['actor'])) {
511 $actor = self::processElement($activity, 'actor', 'id');
516 if (is_string($activity['object'])) {
517 $object_url = $activity['object'];
518 } elseif (!empty($activity['object']['id'])) {
519 $object_url = $activity['object']['id'];
524 $receivers = self::getReceivers($activity);
525 if (empty($receivers)) {
529 // ----------------------------------
531 unset($activity['@context']);
532 unset($activity['id']);
535 unset($activity['title']);
536 unset($activity['atomUri']);
537 unset($activity['context_id']);
538 unset($activity['statusnetConversationId']);
540 $structure = $activity;
543 unset($activity['context']);
544 unset($activity['location']);
547 unset($activity['to']);
548 unset($activity['cc']);
549 unset($activity['bto']);
550 unset($activity['bcc']);
551 unset($activity['type']);
552 unset($activity['actor']);
553 unset($activity['object']);
554 unset($activity['published']);
555 unset($activity['updated']);
556 unset($activity['instrument']);
557 unset($activity['inReplyTo']);
559 if (!empty($activity)) {
565 $activity = $structure;
566 // ----------------------------------
568 $item = self::fetchObject($object_url, $url);
573 $item = self::addActivityFields($item, $activity);
575 $item['owner'] = $actor;
577 $item['receiver'] = array_merge($item['receiver'], $receivers);
579 switch ($activity['type']) {
582 self::createItem($item);
586 self::announceItem($item);
591 self::activityItem($item);
598 echo "Unknown activity: ".$activity['type']."\n";
605 private static function getReceivers($activity)
609 $elements = ['to', 'cc', 'bto', 'bcc'];
610 foreach ($elements as $element) {
611 if (empty($activity[$element])) {
615 // The receiver can be an arror or a string
616 if (is_string($activity[$element])) {
617 $activity[$element] = [$activity[$element]];
620 foreach ($activity[$element] as $receiver) {
621 if ($receiver == self::PUBLIC) {
622 $receivers[$receiver] = 0;
625 $condition = ['self' => true, 'nurl' => normalise_link($receiver)];
626 $contact = DBA::selectFirst('contact', ['id'], $condition);
627 if (!DBA::isResult($contact)) {
630 $receivers[$receiver] = $contact['id'];
636 private static function addActivityFields($item, $activity)
638 if (!empty($activity['published']) && empty($item['published'])) {
639 $item['published'] = $activity['published'];
642 if (!empty($activity['updated']) && empty($item['updated'])) {
643 $item['updated'] = $activity['updated'];
646 if (!empty($activity['inReplyTo']) && empty($item['parent-uri'])) {
647 $item['parent-uri'] = self::processElement($activity, 'inReplyTo', 'id');
650 if (!empty($activity['instrument'])) {
651 $item['service'] = self::processElement($activity, 'instrument', 'name', 'Service');
654 // Remove all "null" fields
655 foreach ($item as $field => $content) {
656 if (is_null($content)) {
657 unset($item[$field]);
664 private static function fetchObject($object_url, $url)
666 $data = self::fetchContent($object_url);
671 if (empty($data['type'])) {
674 $type = $data['type'];
677 if (in_array($type, ['Note', 'Article', 'Video'])) {
678 $common = self::processCommonData($data, $url);
683 return array_merge($common, self::processNote($data, $url));
685 return array_merge($common, self::processArticle($data, $url));
687 return array_merge($common, self::processVideo($data, $url));
690 if (empty($data['object'])) {
693 return self::fetchObject($data['object'], $url);
700 echo "Unknown object type: ".$data['type']."\n";
707 private static function processCommonData(&$object, $url)
709 if (empty($object['id']) || empty($object['attributedTo'])) {
714 $item['uri'] = $object['id'];
716 if (!empty($object['inReplyTo'])) {
717 $item['reply-to-uri'] = self::processElement($object, 'inReplyTo', 'id');
719 $item['reply-to-uri'] = $item['uri'];
722 $item['published'] = defaults($object, 'published', null);
723 $item['updated'] = defaults($object, 'updated', $item['published']);
725 if (empty($item['published']) && !empty($item['updated'])) {
726 $item['published'] = $item['updated'];
729 $item['uuid'] = defaults($object, 'uuid', null);
730 $item['owner'] = $item['author'] = self::processElement($object, 'attributedTo', 'id');
731 $item['context'] = defaults($object, 'context', null);
732 $item['conversation'] = defaults($object, 'conversation', null);
733 $item['sensitive'] = defaults($object, 'sensitive', null);
734 $item['name'] = defaults($object, 'title', null);
735 $item['name'] = defaults($object, 'name', $item['name']);
736 $item['summary'] = defaults($object, 'summary', null);
737 $item['content'] = defaults($object, 'content', null);
738 $item['location'] = self::processElement($object, 'location', 'name', 'Place');
739 $item['attachments'] = defaults($object, 'attachment', null);
740 $item['tags'] = defaults($object, 'tag', null);
741 $item['service'] = self::processElement($object, 'instrument', 'name', 'Service');
742 $item['alternate-url'] = self::processElement($object, 'url', 'href');
743 $item['receiver'] = self::getReceivers($object);
746 unset($object['id']);
747 unset($object['inReplyTo']);
748 unset($object['published']);
749 unset($object['updated']);
750 unset($object['uuid']);
751 unset($object['attributedTo']);
752 unset($object['context']);
753 unset($object['conversation']);
754 unset($object['sensitive']);
755 unset($object['name']);
756 unset($object['title']);
757 unset($object['content']);
758 unset($object['summary']);
759 unset($object['location']);
760 unset($object['attachment']);
761 unset($object['tag']);
762 unset($object['instrument']);
763 unset($object['url']);
764 unset($object['to']);
765 unset($object['cc']);
766 unset($object['bto']);
767 unset($object['bcc']);
770 unset($object['source']);
773 unset($object['@context']);
774 unset($object['type']);
775 unset($object['actor']);
776 unset($object['signature']);
777 unset($object['mediaType']);
778 unset($object['duration']);
779 unset($object['replies']);
780 unset($object['icon']);
783 audience, preview, endTime, startTime, generator, image
789 private static function processNote($object, $url)
794 unset($object['emoji']);
795 unset($object['atomUri']);
796 unset($object['inReplyToAtomUri']);
799 unset($object['contentMap']);
800 unset($object['announcement_count']);
801 unset($object['announcements']);
802 unset($object['context_id']);
803 unset($object['likes']);
804 unset($object['like_count']);
805 unset($object['inReplyToStatusId']);
806 unset($object['shares']);
807 unset($object['quoteUrl']);
808 unset($object['statusnetConversationId']);
813 echo "Unknown Note\n";
821 private static function processArticle($object, $url)
828 echo "Unknown Article\n";
836 private static function processVideo($object, $url)
841 unset($object['category']);
842 unset($object['licence']);
843 unset($object['language']);
844 unset($object['commentsEnabled']);
847 unset($object['views']);
848 unset($object['waitTranscoding']);
849 unset($object['state']);
850 unset($object['support']);
851 unset($object['subtitleLanguage']);
852 unset($object['likes']);
853 unset($object['dislikes']);
854 unset($object['shares']);
855 unset($object['comments']);
860 echo "Unknown Video\n";
868 private static function processElement($array, $element, $key, $type = null)
874 if (empty($array[$element])) {
878 if (is_string($array[$element])) {
879 return $array[$element];
882 if (is_null($type)) {
883 if (!empty($array[$element][$key])) {
884 return $array[$element][$key];
887 if (!empty($array[$element][0][$key])) {
888 return $array[$element][0][$key];
894 if (!empty($array[$element][$key]) && !empty($array[$element]['type']) && ($array[$element]['type'] == $type)) {
895 return $array[$element][$key];
898 /// @todo Add array search
903 private static function createItem($item)
908 private static function announceItem($item)
913 private static function activityItem($item)