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/
31 const PUBLIC = 'https://www.w3.org/ns/activitystreams#Public';
33 public static function transmit($content, $target, $uid)
35 $owner = User::getOwnerDataById($uid);
41 $host = parse_url($target, PHP_URL_HOST);
42 $path = parse_url($target, PHP_URL_PATH);
45 $headers = ['Host: ' . $host, 'Date: ' . $date];
47 $signed_data = "(request-target): post " . $path . "\nhost: " . $host . "\ndate: " . $date;
49 $signature = base64_encode(Crypto::rsaSign($signed_data, $owner['uprvkey'], 'sha256'));
51 $headers[] = 'Signature: keyId="' . $owner['url'] . '#main-key' . '",headers="(request-target) host date",signature="' . $signature . '"';
52 $headers[] = 'Content-Type: application/activity+json';
56 // $headers = HTTPSignature::createSig('', $headers, $owner['uprvkey'], $owner['url'] . '#main-key', false, false, 'sha256');
58 Network::post($target, $content, $headers);
59 $return_code = BaseObject::getApp()->get_curl_code();
60 echo $return_code."\n";
61 print_r(BaseObject::getApp()->get_curl_headers());
66 * Return the ActivityPub profile of the given user
68 * @param integer $uid User ID
71 public static function profile($uid)
73 $accounttype = ['Person', 'Organization', 'Service', 'Group', 'Application'];
75 $condition = ['uid' => $uid, 'blocked' => false, 'account_expired' => false,
76 'account_removed' => false, 'verified' => true];
77 $fields = ['guid', 'nickname', 'pubkey', 'account-type'];
78 $user = DBA::selectFirst('user', $fields, $condition);
79 if (!DBA::isResult($user)) {
83 $fields = ['locality', 'region', 'country-name'];
84 $profile = DBA::selectFirst('profile', $fields, ['uid' => $uid, 'is-default' => true]);
85 if (!DBA::isResult($profile)) {
89 $fields = ['name', 'url', 'location', 'about', 'avatar'];
90 $contact = DBA::selectFirst('contact', $fields, ['uid' => $uid, 'self' => true]);
91 if (!DBA::isResult($contact)) {
95 $data = ['@context' => ['https://www.w3.org/ns/activitystreams', 'https://w3id.org/security/v1',
96 ['uuid' => 'http://schema.org/identifier', 'sensitive' => 'as:sensitive',
97 'vcard' => 'http://www.w3.org/2006/vcard/ns#']]];
99 $data['id'] = $contact['url'];
100 $data['uuid'] = $user['guid'];
101 $data['type'] = $accounttype[$user['account-type']];
102 $data['following'] = System::baseUrl() . '/following/' . $user['nickname'];
103 $data['followers'] = System::baseUrl() . '/followers/' . $user['nickname'];
104 $data['inbox'] = System::baseUrl() . '/inbox/' . $user['nickname'];
105 $data['outbox'] = System::baseUrl() . '/outbox/' . $user['nickname'];
106 $data['preferredUsername'] = $user['nickname'];
107 $data['name'] = $contact['name'];
108 $data['vcard:hasAddress'] = ['@type' => 'Home', 'vcard:country-name' => $profile['country-name'],
109 'vcard:region' => $profile['region'], 'vcard:locality' => $profile['locality']];
110 $data['summary'] = $contact['about'];
111 $data['url'] = $contact['url'];
112 $data['manuallyApprovesFollowers'] = false;
113 $data['publicKey'] = ['id' => $contact['url'] . '#main-key',
114 'owner' => $contact['url'],
115 'publicKeyPem' => $user['pubkey']];
116 $data['endpoints'] = ['sharedInbox' => System::baseUrl() . '/inbox'];
117 $data['icon'] = ['type' => 'Image',
118 'url' => $contact['avatar']];
120 // tags: https://kitty.town/@inmysocks/100656097926961126.json
124 public static function createActivityFromItem($item_id)
126 $item = Item::selectFirst([], ['id' => $item_id]);
128 $data = ['@context' => ['https://www.w3.org/ns/activitystreams', 'https://w3id.org/security/v1',
129 ['Emoji' => 'toot:Emoji', 'Hashtag' => 'as:Hashtag', 'atomUri' => 'ostatus:atomUri',
130 'conversation' => 'ostatus:conversation', 'inReplyToAtomUri' => 'ostatus:inReplyToAtomUri',
131 'ostatus' => 'http://ostatus.org#', 'sensitive' => 'as:sensitive',
132 'toot' => 'http://joinmastodon.org/ns#']]];
134 $data['type'] = 'Create';
135 $data['id'] = $item['plink'];
136 $data['actor'] = $item['author-link'];
137 $data['to'] = 'https://www.w3.org/ns/activitystreams#Public';
138 $data['object'] = self::createNote($item);
144 public static function createNote($item)
147 $data['type'] = 'Note';
148 $data['id'] = $item['plink'];
149 //$data['context'] = $data['conversation'] = $item['parent-uri'];
150 $data['actor'] = $item['author-link'];
151 // if (!$item['private']) {
153 // $data['to'][] = '"https://pleroma.soykaf.com/users/heluecht"';
154 $data['to'] = 'https://www.w3.org/ns/activitystreams#Public';
155 // $data['cc'] = 'https://pleroma.soykaf.com/users/heluecht';
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['title'] = BBCode::convert($item['title'], false, 7);
161 $data['content'] = BBCode::convert($item['body'], false, 7);
162 //$data['summary'] = '';
163 //$data['sensitive'] = false;
164 //$data['emoji'] = [];
166 //$data['attachment'] = [];
171 * Fetches ActivityPub content from the given url
173 * @param string $url content url
176 public static function fetchContent($url)
178 $ret = Network::curl($url, false, $redirects, ['accept_content' => 'application/activity+json']);
180 if (!$ret['success'] || empty($ret['body'])) {
184 return json_decode($ret['body'], true);
188 * Resolves the profile url from the address by using webfinger
190 * @param string $addr profile address (user@domain.tld)
193 private static function addrToUrl($addr)
195 $addr_parts = explode('@', $addr);
196 if (count($addr_parts) != 2) {
200 $webfinger = 'https://' . $addr_parts[1] . '/.well-known/webfinger?resource=acct:' . urlencode($addr);
202 $ret = Network::curl($webfinger, false, $redirects, ['accept_content' => 'application/jrd+json,application/json']);
203 if (!$ret['success'] || empty($ret['body'])) {
207 $data = json_decode($ret['body'], true);
209 if (empty($data['links'])) {
213 foreach ($data['links'] as $link) {
214 if (empty($link['href']) || empty($link['rel']) || empty($link['type'])) {
218 if (($link['rel'] == 'self') && ($link['type'] == 'application/activity+json')) {
219 return $link['href'];
227 * Fetches a profile from the given url
229 * @param string $url profile url
232 public static function fetchProfile($url)
234 if (empty(parse_url($url, PHP_URL_SCHEME))) {
235 $url = self::addrToUrl($url);
241 $data = self::fetchContent($url);
243 if (empty($data) || empty($data['id']) || empty($data['inbox'])) {
247 $profile = ['network' => Protocol::ACTIVITYPUB];
248 $profile['nick'] = $data['preferredUsername'];
249 $profile['name'] = defaults($data, 'name', $profile['nick']);
250 $profile['guid'] = defaults($data, 'uuid', null);
251 $profile['url'] = $data['id'];
252 $profile['alias'] = self::processElement($data, 'url', 'href');
254 $parts = parse_url($profile['url']);
255 unset($parts['scheme']);
256 unset($parts['path']);
257 $profile['addr'] = $profile['nick'] . '@' . str_replace('//', '', Network::unparseURL($parts));
259 $profile['photo'] = self::processElement($data, 'icon', 'url');
260 $profile['about'] = defaults($data, 'summary', '');
261 $profile['batch'] = self::processElement($data, 'endpoints', 'sharedInbox');
262 $profile['pubkey'] = self::processElement($data, 'publicKey', 'publicKeyPem');
263 $profile['notify'] = $data['inbox'];
264 $profile['poll'] = $data['outbox'];
266 // Check if the address is resolvable
267 if (self::addrToUrl($profile['addr']) == $profile['url']) {
268 $parts = parse_url($profile['url']);
269 unset($parts['path']);
270 $profile['baseurl'] = Network::unparseURL($parts);
272 unset($profile['addr']);
275 if ($profile['url'] == $profile['alias']) {
276 unset($profile['alias']);
279 // Remove all "null" fields
280 foreach ($profile as $field => $content) {
281 if (is_null($content)) {
282 unset($profile[$field]);
288 unset($data['inbox']);
289 unset($data['outbox']);
290 unset($data['preferredUsername']);
291 unset($data['name']);
292 unset($data['summary']);
294 unset($data['publicKey']);
295 unset($data['endpoints']);
296 unset($data['icon']);
297 unset($data['uuid']);
300 unset($data['type']);
301 unset($data['manuallyApprovesFollowers']);
304 unset($data['@context']);
306 unset($data['attachment']);
307 unset($data['image']);
308 unset($data['nomadicLocations']);
309 unset($data['signature']);
310 unset($data['following']);
311 unset($data['followers']);
312 unset($data['featured']);
313 unset($data['movedTo']);
314 unset($data['liked']);
315 unset($data['sharedInbox']); // Misskey
316 unset($data['isCat']); // Misskey
317 unset($data['kroeg:blocks']); // Kroeg
318 unset($data['updated']); // Kroeg
320 /* if (!empty($data)) {
328 public static function fetchOutbox($url)
330 $data = self::fetchContent($url);
335 if (!empty($data['orderedItems'])) {
336 $items = $data['orderedItems'];
337 } elseif (!empty($data['first']['orderedItems'])) {
338 $items = $data['first']['orderedItems'];
339 } elseif (!empty($data['first'])) {
340 self::fetchOutbox($data['first']);
346 foreach ($items as $activity) {
347 self::processActivity($activity, $url);
351 function processActivity($activity, $url)
353 if (empty($activity['type'])) {
357 if (empty($activity['object'])) {
361 if (empty($activity['actor'])) {
365 $actor = self::processElement($activity, 'actor', 'id');
370 if (is_string($activity['object'])) {
371 $object_url = $activity['object'];
372 } elseif (!empty($activity['object']['id'])) {
373 $object_url = $activity['object']['id'];
378 $receivers = self::getReceivers($activity);
379 if (empty($receivers)) {
383 // ----------------------------------
385 unset($activity['@context']);
386 unset($activity['id']);
389 unset($activity['title']);
390 unset($activity['atomUri']);
391 unset($activity['context_id']);
392 unset($activity['statusnetConversationId']);
394 $structure = $activity;
397 unset($activity['context']);
398 unset($activity['location']);
401 unset($activity['to']);
402 unset($activity['cc']);
403 unset($activity['bto']);
404 unset($activity['bcc']);
405 unset($activity['type']);
406 unset($activity['actor']);
407 unset($activity['object']);
408 unset($activity['published']);
409 unset($activity['updated']);
410 unset($activity['instrument']);
411 unset($activity['inReplyTo']);
413 if (!empty($activity)) {
419 $activity = $structure;
420 // ----------------------------------
422 $item = self::fetchObject($object_url, $url);
427 $item = self::addActivityFields($item, $activity);
429 $item['owner'] = $actor;
431 $item['receiver'] = array_merge($item['receiver'], $receivers);
433 switch ($activity['type']) {
436 self::createItem($item);
440 self::announceItem($item);
445 self::activityItem($item);
452 echo "Unknown activity: ".$activity['type']."\n";
459 private static function getReceivers($activity)
463 $elements = ['to', 'cc', 'bto', 'bcc'];
464 foreach ($elements as $element) {
465 if (empty($activity[$element])) {
469 // The receiver can be an arror or a string
470 if (is_string($activity[$element])) {
471 $activity[$element] = [$activity[$element]];
474 foreach ($activity[$element] as $receiver) {
475 if ($receiver == self::PUBLIC) {
476 $receivers[$receiver] = 0;
479 $condition = ['self' => true, 'nurl' => normalise_link($receiver)];
480 $contact = DBA::selectFirst('contact', ['id'], $condition);
481 if (!DBA::isResult($contact)) {
484 $receivers[$receiver] = $contact['id'];
490 private static function addActivityFields($item, $activity)
492 if (!empty($activity['published']) && empty($item['published'])) {
493 $item['published'] = $activity['published'];
496 if (!empty($activity['updated']) && empty($item['updated'])) {
497 $item['updated'] = $activity['updated'];
500 if (!empty($activity['inReplyTo']) && empty($item['parent-uri'])) {
501 $item['parent-uri'] = self::processElement($activity, 'inReplyTo', 'id');
504 if (!empty($activity['instrument'])) {
505 $item['service'] = self::processElement($activity, 'instrument', 'name', 'Service');
508 // Remove all "null" fields
509 foreach ($item as $field => $content) {
510 if (is_null($content)) {
511 unset($item[$field]);
518 private static function fetchObject($object_url, $url)
520 $data = self::fetchContent($object_url);
525 if (empty($data['type'])) {
528 $type = $data['type'];
531 if (in_array($type, ['Note', 'Article', 'Video'])) {
532 $common = self::processCommonData($data, $url);
537 return array_merge($common, self::processNote($data, $url));
539 return array_merge($common, self::processArticle($data, $url));
541 return array_merge($common, self::processVideo($data, $url));
544 if (empty($data['object'])) {
547 return self::fetchObject($data['object'], $url);
554 echo "Unknown object type: ".$data['type']."\n";
561 private static function processCommonData(&$object, $url)
563 if (empty($object['id']) || empty($object['attributedTo'])) {
568 $item['uri'] = $object['id'];
570 if (!empty($object['inReplyTo'])) {
571 $item['reply-to-uri'] = self::processElement($object, 'inReplyTo', 'id');
573 $item['reply-to-uri'] = $item['uri'];
576 $item['published'] = defaults($object, 'published', null);
577 $item['updated'] = defaults($object, 'updated', $item['published']);
579 if (empty($item['published']) && !empty($item['updated'])) {
580 $item['published'] = $item['updated'];
583 $item['uuid'] = defaults($object, 'uuid', null);
584 $item['owner'] = $item['author'] = self::processElement($object, 'attributedTo', 'id');
585 $item['context'] = defaults($object, 'context', null);
586 $item['conversation'] = defaults($object, 'conversation', null);
587 $item['sensitive'] = defaults($object, 'sensitive', null);
588 $item['name'] = defaults($object, 'name', null);
589 $item['title'] = defaults($object, 'title', null);
590 $item['content'] = defaults($object, 'content', null);
591 $item['summary'] = defaults($object, 'summary', null);
592 $item['location'] = self::processElement($object, 'location', 'name', 'Place');
593 $item['attachments'] = defaults($object, 'attachment', null);
594 $item['tags'] = defaults($object, 'tag', null);
595 $item['service'] = self::processElement($object, 'instrument', 'name', 'Service');
596 $item['alternate-url'] = self::processElement($object, 'url', 'href');
597 $item['receiver'] = self::getReceivers($object);
600 unset($object['id']);
601 unset($object['inReplyTo']);
602 unset($object['published']);
603 unset($object['updated']);
604 unset($object['uuid']);
605 unset($object['attributedTo']);
606 unset($object['context']);
607 unset($object['conversation']);
608 unset($object['sensitive']);
609 unset($object['name']);
610 unset($object['title']);
611 unset($object['content']);
612 unset($object['summary']);
613 unset($object['location']);
614 unset($object['attachment']);
615 unset($object['tag']);
616 unset($object['instrument']);
617 unset($object['url']);
618 unset($object['to']);
619 unset($object['cc']);
620 unset($object['bto']);
621 unset($object['bcc']);
624 unset($object['source']);
627 unset($object['@context']);
628 unset($object['type']);
629 unset($object['actor']);
630 unset($object['signature']);
631 unset($object['mediaType']);
632 unset($object['duration']);
633 unset($object['replies']);
634 unset($object['icon']);
637 audience, preview, endTime, startTime, generator, image
643 private static function processNote($object, $url)
648 unset($object['emoji']);
649 unset($object['atomUri']);
650 unset($object['inReplyToAtomUri']);
653 unset($object['contentMap']);
654 unset($object['announcement_count']);
655 unset($object['announcements']);
656 unset($object['context_id']);
657 unset($object['likes']);
658 unset($object['like_count']);
659 unset($object['inReplyToStatusId']);
660 unset($object['shares']);
661 unset($object['quoteUrl']);
662 unset($object['statusnetConversationId']);
667 echo "Unknown Note\n";
675 private static function processArticle($object, $url)
682 echo "Unknown Article\n";
690 private static function processVideo($object, $url)
695 unset($object['category']);
696 unset($object['licence']);
697 unset($object['language']);
698 unset($object['commentsEnabled']);
701 unset($object['views']);
702 unset($object['waitTranscoding']);
703 unset($object['state']);
704 unset($object['support']);
705 unset($object['subtitleLanguage']);
706 unset($object['likes']);
707 unset($object['dislikes']);
708 unset($object['shares']);
709 unset($object['comments']);
714 echo "Unknown Video\n";
722 private static function processElement($array, $element, $key, $type = null)
728 if (empty($array[$element])) {
732 if (is_string($array[$element])) {
733 return $array[$element];
736 if (is_null($type)) {
737 if (!empty($array[$element][$key])) {
738 return $array[$element][$key];
741 if (!empty($array[$element][0][$key])) {
742 return $array[$element][0][$key];
748 if (!empty($array[$element][$key]) && !empty($array[$element]['type']) && ($array[$element]['type'] == $type)) {
749 return $array[$element][$key];
752 /// @todo Add array search
757 private static function createItem($item)
762 private static function announceItem($item)
767 private static function activityItem($item)