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\Conversation;
14 use Friendica\Model\Contact;
15 use Friendica\Model\Item;
16 use Friendica\Model\Term;
17 use Friendica\Model\User;
18 use Friendica\Util\DateTimeFormat;
19 use Friendica\Util\Crypto;
20 use Friendica\Content\Text\BBCode;
21 use Friendica\Content\Text\HTML;
22 use Friendica\Network\Probe;
25 * @brief ActivityPub Protocol class
26 * The ActivityPub Protocol is a message exchange protocol defined by the W3C.
27 * https://www.w3.org/TR/activitypub/
28 * https://www.w3.org/TR/activitystreams-core/
29 * https://www.w3.org/TR/activitystreams-vocabulary/
31 * https://blog.joinmastodon.org/2018/06/how-to-implement-a-basic-activitypub-server/
32 * https://blog.joinmastodon.org/2018/07/how-to-make-friends-and-verify-requests/
34 * Digest: https://tools.ietf.org/html/rfc5843
35 * https://tools.ietf.org/html/draft-cavage-http-signatures-10#ref-15
36 * https://github.com/digitalbazaar/php-json-ld
38 * Part of the code for HTTP signing is taken from the Osada project.
39 * https://framagit.org/macgirvin/osada
44 * - Activities: Dislike, Update, Delete
45 * - Object Types: Person, Tombstome
48 * - Activities: Like, Dislike, Update, Delete
49 * - Object Tyoes: Article, Announce, Person, Tombstone
52 * - Message distribution
53 * - Endpoints: Outbox, Object, Follower, Following
58 const PUBLIC = 'https://www.w3.org/ns/activitystreams#Public';
60 public static function isRequest()
62 return stristr(defaults($_SERVER, 'HTTP_ACCEPT', ''), 'application/activity+json') ||
63 stristr(defaults($_SERVER, 'HTTP_ACCEPT', ''), 'application/ld+json');
66 public static function transmit($data, $target, $uid)
68 $owner = User::getOwnerDataById($uid);
74 $content = json_encode($data);
76 // Header data that is about to be signed.
77 $host = parse_url($target, PHP_URL_HOST);
78 $path = parse_url($target, PHP_URL_PATH);
79 $digest = 'SHA-256=' . base64_encode(hash('sha256', $content, true));
80 $content_length = strlen($content);
82 $headers = ['Content-Length: ' . $content_length, 'Digest: ' . $digest, 'Host: ' . $host];
84 $signed_data = "(request-target): post " . $path . "\ncontent-length: " . $content_length . "\ndigest: " . $digest . "\nhost: " . $host;
86 $signature = base64_encode(Crypto::rsaSign($signed_data, $owner['uprvkey'], 'sha256'));
88 $headers[] = 'Signature: keyId="' . $owner['url'] . '#main-key' . '",algorithm="rsa-sha256",headers="(request-target) content-length digest host",signature="' . $signature . '"';
90 $headers[] = 'Content-Type: application/activity+json';
92 Network::post($target, $content, $headers);
93 $return_code = BaseObject::getApp()->get_curl_code();
95 logger('Transmit to ' . $target . ' returned ' . $return_code);
99 * Return the ActivityPub profile of the given user
101 * @param integer $uid User ID
104 public static function profile($uid)
106 $accounttype = ['Person', 'Organization', 'Service', 'Group', 'Application', 'page-flags'];
107 $condition = ['uid' => $uid, 'blocked' => false, 'account_expired' => false,
108 'account_removed' => false, 'verified' => true];
109 $fields = ['guid', 'nickname', 'pubkey', 'account-type'];
110 $user = DBA::selectFirst('user', $fields, $condition);
111 if (!DBA::isResult($user)) {
115 $fields = ['locality', 'region', 'country-name'];
116 $profile = DBA::selectFirst('profile', $fields, ['uid' => $uid, 'is-default' => true]);
117 if (!DBA::isResult($profile)) {
121 $fields = ['name', 'url', 'location', 'about', 'avatar'];
122 $contact = DBA::selectFirst('contact', $fields, ['uid' => $uid, 'self' => true]);
123 if (!DBA::isResult($contact)) {
127 $data = ['@context' => ['https://www.w3.org/ns/activitystreams', 'https://w3id.org/security/v1',
128 ['vcard' => 'http://www.w3.org/2006/vcard/ns#', 'uuid' => 'http://schema.org/identifier',
129 'sensitive' => 'as:sensitive', 'manuallyApprovesFollowers' => 'as:manuallyApprovesFollowers']]];
131 $data['id'] = $contact['url'];
132 $data['uuid'] = $user['guid'];
133 $data['type'] = $accounttype[$user['account-type']];
134 $data['following'] = System::baseUrl() . '/following/' . $user['nickname'];
135 $data['followers'] = System::baseUrl() . '/followers/' . $user['nickname'];
136 $data['inbox'] = System::baseUrl() . '/inbox/' . $user['nickname'];
137 $data['outbox'] = System::baseUrl() . '/outbox/' . $user['nickname'];
138 $data['preferredUsername'] = $user['nickname'];
139 $data['name'] = $contact['name'];
140 $data['vcard:hasAddress'] = ['@type' => 'vcard:Home', 'vcard:country-name' => $profile['country-name'],
141 'vcard:region' => $profile['region'], 'vcard:locality' => $profile['locality']];
142 $data['summary'] = $contact['about'];
143 $data['url'] = $contact['url'];
144 $data['manuallyApprovesFollowers'] = in_array($profile['page-flags'], [Contact::PAGE_NORMAL, Contact::PAGE_PRVGROUP]);
145 $data['publicKey'] = ['id' => $contact['url'] . '#main-key',
146 'owner' => $contact['url'],
147 'publicKeyPem' => $user['pubkey']];
148 $data['endpoints'] = ['sharedInbox' => System::baseUrl() . '/inbox'];
149 $data['icon'] = ['type' => 'Image',
150 'url' => $contact['avatar']];
152 // tags: https://kitty.town/@inmysocks/100656097926961126.json
156 public static function createPermissionBlockForItem($item)
158 $data = ['to' => [], 'cc' => []];
160 $terms = Term::tagArrayFromItemId($item['id']);
162 if (!$item['private']) {
163 $data['to'][] = self::PUBLIC;
164 $data['cc'][] = System::baseUrl() . '/followers/' . $item['author-nick'];
166 foreach ($terms as $term) {
167 if ($term['type'] != TERM_MENTION) {
170 $profile = Probe::uri($term['url'], Protocol::ACTIVITYPUB);
171 if ($profile['network'] == Protocol::ACTIVITYPUB) {
172 $data['cc'][] = $profile['url'];
176 //$data['cc'][] = System::baseUrl() . '/followers/' . $item['author-nick'];
177 $receiver_list = Item::enumeratePermissions($item);
181 foreach ($terms as $term) {
182 if ($term['type'] != TERM_MENTION) {
185 $cid = Contact::getIdForURL($term['url'], $item['uid']);
186 if (!empty($cid) && in_array($cid, $receiver_list)) {
187 $contact = DBA::selectFirst('contact', ['url'], ['id' => $cid, 'network' => Protocol::ACTIVITYPUB]);
188 $data['to'][] = $contact['url'];
192 foreach ($receiver_list as $receiver) {
193 $contact = DBA::selectFirst('contact', ['url'], ['id' => $receiver, 'network' => Protocol::ACTIVITYPUB]);
194 $data['cc'][] = $contact['url'];
197 if (empty($data['to'])) {
198 $data['to'] = $data['cc'];
206 public static function fetchTargetInboxes($item)
210 $terms = Term::tagArrayFromItemId($item['id']);
211 if (!$item['private']) {
212 $contacts = DBA::select('contact', ['notify', 'batch'], ['uid' => $item['uid'],
213 'rel' => [Contact::FOLLOWER, Contact::FRIEND], 'network' => Protocol::ACTIVITYPUB]);
214 while ($contact = DBA::fetch($contacts)) {
215 $contact = defaults($contact, 'batch', $contact['notify']);
216 $inboxes[$contact] = $contact;
218 DBA::close($contacts);
220 foreach ($terms as $term) {
221 if ($term['type'] != TERM_MENTION) {
224 $profile = Probe::uri($term['url'], Protocol::ACTIVITYPUB);
225 if ($profile['network'] == Protocol::ACTIVITYPUB) {
226 $target = defaults($profile, 'batch', $profile['notify']);
227 $inboxes[$target] = $target;
231 $receiver_list = Item::enumeratePermissions($item);
235 foreach ($terms as $term) {
236 if ($term['type'] != TERM_MENTION) {
239 $cid = Contact::getIdForURL($term['url'], $item['uid']);
240 if (!empty($cid) && in_array($cid, $receiver_list)) {
241 $contact = DBA::selectFirst('contact', ['url'], ['id' => $cid, 'network' => Protocol::ACTIVITYPUB]);
242 $profile = Probe::uri($contact['url'], Protocol::ACTIVITYPUB);
243 if ($profile['network'] == Protocol::ACTIVITYPUB) {
244 $target = defaults($profile, 'batch', $profile['notify']);
245 $inboxes[$target] = $target;
250 foreach ($receiver_list as $receiver) {
251 $contact = DBA::selectFirst('contact', ['url'], ['id' => $receiver, 'network' => Protocol::ACTIVITYPUB]);
252 $profile = Probe::uri($contact['url'], Protocol::ACTIVITYPUB);
253 if ($profile['network'] == Protocol::ACTIVITYPUB) {
254 $target = defaults($profile, 'batch', $profile['notify']);
255 $inboxes[$target] = $target;
260 $profile = Probe::uri($target, Protocol::ACTIVITYPUB);
261 if (!empty($profile['batch'])) {
262 unset($inboxes[$profile['batch']]);
265 if (!empty($profile['notify'])) {
266 unset($inboxes[$profile['notify']]);
272 public static function createActivityFromItem($item_id)
274 $item = Item::selectFirst([], ['id' => $item_id]);
276 if (!DBA::isResult($item)) {
280 $condition = ['item-uri' => $item['uri'], 'protocol' => Conversation::PARCEL_ACTIVITYPUB];
281 $conversation = DBA::selectFirst('conversation', ['source'], $condition);
282 if (DBA::isResult($conversation)) {
283 $data = json_decode($conversation['source']);
289 $data = ['@context' => ['https://www.w3.org/ns/activitystreams', 'https://w3id.org/security/v1',
290 ['ostatus' => 'http://ostatus.org#', 'sensitive' => 'as:sensitive',
291 'Hashtag' => 'as:Hashtag', 'atomUri' => 'ostatus:atomUri',
292 'conversation' => 'ostatus:conversation',
293 'inReplyToAtomUri' => 'ostatus:inReplyToAtomUri']]];
295 $data['type'] = 'Create';
296 $data['id'] = $item['uri'] . '#activity';
297 $data['actor'] = $item['author-link'];
299 $data['published'] = DateTimeFormat::utc($item["created"]."+00:00", DateTimeFormat::ATOM);
301 if ($item["created"] != $item["edited"]) {
302 $data['updated'] = DateTimeFormat::utc($item["edited"]."+00:00", DateTimeFormat::ATOM);
305 $data = array_merge($data, ActivityPub::createPermissionBlockForItem($item));
307 $data['object'] = self::createNote($item);
311 public static function createObjectFromItemID($item_id)
313 $item = Item::selectFirst([], ['id' => $item_id]);
315 if (!DBA::isResult($item)) {
319 $data = ['@context' => ['https://www.w3.org/ns/activitystreams', 'https://w3id.org/security/v1',
320 ['ostatus' => 'http://ostatus.org#', 'sensitive' => 'as:sensitive',
321 'Hashtag' => 'as:Hashtag', 'atomUri' => 'ostatus:atomUri',
322 'conversation' => 'ostatus:conversation',
323 'inReplyToAtomUri' => 'ostatus:inReplyToAtomUri']]];
325 $data = array_merge($data, self::createNote($item));
331 private static function createTagList($item)
335 $terms = Term::tagArrayFromItemId($item['id']);
336 foreach ($terms as $term) {
337 if ($term['type'] == TERM_MENTION) {
338 $contact = Contact::getDetailsByURL($term['url']);
339 if (!empty($contact['addr'])) {
340 $mention = '@' . $contact['addr'];
342 $mention = '@' . $term['url'];
345 $tags[] = ['type' => 'Mention', 'href' => $term['url'], 'name' => $mention];
352 public static function createNote($item)
355 $data['type'] = 'Note';
356 $data['id'] = $item['uri'];
358 if ($item['uri'] != $item['thr-parent']) {
359 $data['inReplyTo'] = $item['thr-parent'];
362 $conversation = DBA::selectFirst('conversation', ['conversation-uri'], ['item-uri' => $item['parent-uri']]);
363 if (DBA::isResult($conversation) && !empty($conversation['conversation-uri'])) {
364 $conversation_uri = $conversation['conversation-uri'];
366 $conversation_uri = $item['parent-uri'];
369 $data['context'] = $data['conversation'] = $conversation_uri;
370 $data['actor'] = $item['author-link'];
371 $data = array_merge($data, ActivityPub::createPermissionBlockForItem($item));
372 $data['published'] = DateTimeFormat::utc($item["created"]."+00:00", DateTimeFormat::ATOM);
374 if ($item["created"] != $item["edited"]) {
375 $data['updated'] = DateTimeFormat::utc($item["edited"]."+00:00", DateTimeFormat::ATOM);
378 $data['attributedTo'] = $item['author-link'];
379 $data['name'] = BBCode::convert($item['title'], false, 7);
380 $data['content'] = BBCode::convert($item['body'], false, 7);
381 $data['source'] = ['content' => $item['body'], 'mediaType' => "text/bbcode"];
382 $data['summary'] = ''; // Ignore by now
383 $data['sensitive'] = false; // - Query NSFW
384 //$data['emoji'] = []; // Ignore by now
385 $data['tag'] = self::createTagList($item);
386 $data['attachment'] = []; // @ToDo
390 public static function transmitActivity($activity, $target, $uid)
392 $profile = Probe::uri($target, Protocol::ACTIVITYPUB);
394 $owner = User::getOwnerDataById($uid);
396 $data = ['@context' => 'https://www.w3.org/ns/activitystreams',
397 'id' => System::baseUrl() . '/activity/' . System::createGUID(),
399 'actor' => $owner['url'],
400 'object' => $profile['url'],
401 'to' => $profile['url']];
403 logger('Sending activity ' . $activity . ' to ' . $target . ' for user ' . $uid, LOGGER_DEBUG);
404 return self::transmit($data, $profile['notify'], $uid);
407 public static function transmitContactAccept($target, $id, $uid)
409 $profile = Probe::uri($target, Protocol::ACTIVITYPUB);
411 $owner = User::getOwnerDataById($uid);
412 $data = ['@context' => 'https://www.w3.org/ns/activitystreams',
413 'id' => System::baseUrl() . '/activity/' . System::createGUID(),
415 'actor' => $owner['url'],
416 'object' => ['id' => $id, 'type' => 'Follow',
417 'actor' => $profile['url'],
418 'object' => $owner['url']],
419 'to' => $profile['url']];
421 logger('Sending accept to ' . $target . ' for user ' . $uid . ' with id ' . $id, LOGGER_DEBUG);
422 return self::transmit($data, $profile['notify'], $uid);
425 public static function transmitContactReject($target, $id, $uid)
427 $profile = Probe::uri($target, Protocol::ACTIVITYPUB);
429 $owner = User::getOwnerDataById($uid);
430 $data = ['@context' => 'https://www.w3.org/ns/activitystreams',
431 'id' => System::baseUrl() . '/activity/' . System::createGUID(),
433 'actor' => $owner['url'],
434 'object' => ['id' => $id, 'type' => 'Follow',
435 'actor' => $profile['url'],
436 'object' => $owner['url']],
437 'to' => $profile['url']];
439 logger('Sending reject to ' . $target . ' for user ' . $uid . ' with id ' . $id, LOGGER_DEBUG);
440 return self::transmit($data, $profile['notify'], $uid);
443 public static function transmitContactUndo($target, $uid)
445 $profile = Probe::uri($target, Protocol::ACTIVITYPUB);
447 $id = System::baseUrl() . '/activity/' . System::createGUID();
449 $owner = User::getOwnerDataById($uid);
450 $data = ['@context' => 'https://www.w3.org/ns/activitystreams',
453 'actor' => $owner['url'],
454 'object' => ['id' => $id, 'type' => 'Follow',
455 'actor' => $owner['url'],
456 'object' => $profile['url']],
457 'to' => $profile['url']];
459 logger('Sending undo to ' . $target . ' for user ' . $uid . ' with id ' . $id, LOGGER_DEBUG);
460 return self::transmit($data, $profile['notify'], $uid);
464 * Fetches ActivityPub content from the given url
466 * @param string $url content url
469 public static function fetchContent($url)
471 $ret = Network::curl($url, false, $redirects, ['accept_content' => 'application/activity+json, application/ld+json']);
472 if (!$ret['success'] || empty($ret['body'])) {
476 return json_decode($ret['body'], true);
480 * Resolves the profile url from the address by using webfinger
482 * @param string $addr profile address (user@domain.tld)
485 private static function addrToUrl($addr)
487 $addr_parts = explode('@', $addr);
488 if (count($addr_parts) != 2) {
492 $webfinger = 'https://' . $addr_parts[1] . '/.well-known/webfinger?resource=acct:' . urlencode($addr);
494 $ret = Network::curl($webfinger, false, $redirects, ['accept_content' => 'application/jrd+json,application/json']);
495 if (!$ret['success'] || empty($ret['body'])) {
499 $data = json_decode($ret['body'], true);
501 if (empty($data['links'])) {
505 foreach ($data['links'] as $link) {
506 if (empty($link['href']) || empty($link['rel']) || empty($link['type'])) {
510 if (($link['rel'] == 'self') && ($link['type'] == 'application/activity+json')) {
511 return $link['href'];
518 public static function verifySignature($content, $http_headers)
520 $object = json_decode($content, true);
522 if (empty($object)) {
526 $actor = self::processElement($object, 'actor', 'id');
529 $headers['(request-target)'] = strtolower($http_headers['REQUEST_METHOD']) . ' ' . $http_headers['REQUEST_URI'];
531 // First take every header
532 foreach ($http_headers as $k => $v) {
533 $field = str_replace('_', '-', strtolower($k));
534 $headers[$field] = $v;
537 // Now add every http header
538 foreach ($http_headers as $k => $v) {
539 if (strpos($k, 'HTTP_') === 0) {
540 $field = str_replace('_', '-', strtolower(substr($k, 5)));
541 $headers[$field] = $v;
545 $sig_block = ActivityPub::parseSigHeader($http_headers['HTTP_SIGNATURE']);
547 if (empty($sig_block) || empty($sig_block['headers']) || empty($sig_block['keyId'])) {
552 foreach ($sig_block['headers'] as $h) {
553 if (array_key_exists($h, $headers)) {
554 $signed_data .= $h . ': ' . $headers[$h] . "\n";
557 $signed_data = rtrim($signed_data, "\n");
559 if (empty($signed_data)) {
565 if ($sig_block['algorithm'] === 'rsa-sha256') {
566 $algorithm = 'sha256';
569 if ($sig_block['algorithm'] === 'rsa-sha512') {
570 $algorithm = 'sha512';
573 if (empty($algorithm)) {
577 $key = self::fetchKey($sig_block['keyId'], $actor);
583 if (!Crypto::rsaVerify($signed_data, $sig_block['signature'], $key, $algorithm)) {
587 // Check the digest when it is part of the signed data
588 if (in_array('digest', $sig_block['headers'])) {
589 $digest = explode('=', $headers['digest'], 2);
590 if ($digest[0] === 'SHA-256') {
593 if ($digest[0] === 'SHA-512') {
597 /// @todo add all hashes from the rfc
599 if (!empty($hashalg) && base64_encode(hash($hashalg, $content, true)) != $digest[1]) {
604 // Check the content-length when it is part of the signed data
605 if (in_array('content-length', $sig_block['headers'])) {
606 if (strlen($content) != $headers['content-length']) {
615 private static function fetchKey($id, $actor)
617 $url = (strpos($id, '#') ? substr($id, 0, strpos($id, '#')) : $id);
619 $profile = Probe::uri($url, Protocol::ACTIVITYPUB);
620 if (!empty($profile)) {
621 return $profile['pubkey'];
622 } elseif ($url != $actor) {
623 $profile = Probe::uri($actor, Protocol::ACTIVITYPUB);
624 if (!empty($profile)) {
625 return $profile['pubkey'];
635 * @param string $header
636 * @return array associate array with
637 * - \e string \b keyID
638 * - \e string \b algorithm
639 * - \e array \b headers
640 * - \e string \b signature
642 private static function parseSigHeader($header)
647 if (preg_match('/keyId="(.*?)"/ism',$header,$matches)) {
648 $ret['keyId'] = $matches[1];
651 if (preg_match('/algorithm="(.*?)"/ism',$header,$matches)) {
652 $ret['algorithm'] = $matches[1];
655 if (preg_match('/headers="(.*?)"/ism',$header,$matches)) {
656 $ret['headers'] = explode(' ', $matches[1]);
659 if (preg_match('/signature="(.*?)"/ism',$header,$matches)) {
660 $ret['signature'] = base64_decode(preg_replace('/\s+/','',$matches[1]));
667 * Fetches a profile from the given url
669 * @param string $url profile url
672 public static function fetchProfile($url)
674 if (empty(parse_url($url, PHP_URL_SCHEME))) {
675 $url = self::addrToUrl($url);
681 $data = self::fetchContent($url);
683 if (empty($data) || empty($data['id']) || empty($data['inbox'])) {
688 $apcontact['url'] = $data['id'];
689 $apcontact['uuid'] = defaults($data, 'uuid', null);
690 $apcontact['type'] = defaults($data, 'type', null);
691 $apcontact['following'] = defaults($data, 'following', null);
692 $apcontact['followers'] = defaults($data, 'followers', null);
693 $apcontact['inbox'] = defaults($data, 'inbox', null);
694 $apcontact['outbox'] = defaults($data, 'outbox', null);
695 $apcontact['sharedinbox'] = self::processElement($data, 'endpoints', 'sharedInbox');
696 $apcontact['nick'] = defaults($data, 'preferredUsername', null);
697 $apcontact['name'] = defaults($data, 'name', $apcontact['nick']);
698 $apcontact['about'] = defaults($data, 'summary', '');
699 $apcontact['photo'] = self::processElement($data, 'icon', 'url');
700 $apcontact['alias'] = self::processElement($data, 'url', 'href');
702 $parts = parse_url($apcontact['url']);
703 unset($parts['scheme']);
704 unset($parts['path']);
705 $apcontact['addr'] = $apcontact['nick'] . '@' . str_replace('//', '', Network::unparseURL($parts));
707 $apcontact['pubkey'] = self::processElement($data, 'publicKey', 'publicKeyPem');
709 // Check if the address is resolvable
710 if (self::addrToUrl($apcontact['addr']) == $apcontact['url']) {
711 $parts = parse_url($apcontact['url']);
712 unset($parts['path']);
713 $apcontact['baseurl'] = Network::unparseURL($parts);
715 $apcontact['addr'] = null;
718 if ($apcontact['url'] == $apcontact['alias']) {
719 $apcontact['alias'] = null;
722 $apcontact['updated'] = DateTimeFormat::utcNow();
724 DBA::update('apcontact', $apcontact, ['url' => $url], true);
726 // Array that is compatible to Probe::uri
727 $profile = ['network' => Protocol::ACTIVITYPUB];
728 $profile['nick'] = $apcontact['nick'];
729 $profile['name'] = $apcontact['name'];
730 $profile['guid'] = $apcontact['uuid'];
731 $profile['url'] = $apcontact['url'];
732 $profile['addr'] = $apcontact['addr'];
733 $profile['alias'] = $apcontact['alias'];
734 $profile['photo'] = $apcontact['photo'];
735 // $profile['community']
736 // $profile['keywords']
737 // $profile['location']
738 $profile['about'] = $apcontact['about'];
739 $profile['batch'] = $apcontact['sharedinbox'];
740 $profile['notify'] = $apcontact['inbox'];
741 $profile['poll'] = $apcontact['outbox'];
742 $profile['pubkey'] = $apcontact['pubkey'];
743 $profile['baseurl'] = $apcontact['baseurl'];
745 // Remove all "null" fields
746 foreach ($profile as $field => $content) {
747 if (is_null($content)) {
748 unset($profile[$field]);
753 // type, manuallyApprovesFollowers
756 // @context, tag, attachment, image, nomadicLocations, signature, following, followers, featured, movedTo, liked
758 // Unhandled from Misskey
759 // sharedInbox, isCat
761 // Unhandled from Kroeg
762 // kroeg:blocks, updated
767 public static function processInbox($body, $header, $uid)
769 logger('Incoming message for user ' . $uid, LOGGER_DEBUG);
771 if (!self::verifySignature($body, $header)) {
772 logger('Invalid signature, message will be discarded.', LOGGER_DEBUG);
776 $activity = json_decode($body, true);
778 if (!is_array($activity)) {
779 logger('Invalid body.', LOGGER_DEBUG);
783 self::processActivity($activity, $body, $uid);
786 public static function fetchOutbox($url)
788 $data = self::fetchContent($url);
793 if (!empty($data['orderedItems'])) {
794 $items = $data['orderedItems'];
795 } elseif (!empty($data['first']['orderedItems'])) {
796 $items = $data['first']['orderedItems'];
797 } elseif (!empty($data['first'])) {
798 self::fetchOutbox($data['first']);
804 foreach ($items as $activity) {
805 self::processActivity($activity);
809 private static function prepareObjectData($activity, $uid)
811 $actor = self::processElement($activity, 'actor', 'id');
813 logger('Empty actor', LOGGER_DEBUG);
817 // Fetch all receivers from to, cc, bto and bcc
818 $receivers = self::getReceivers($activity, $actor);
820 // When it is a delivery to a personal inbox we add that user to the receivers
822 $owner = User::getOwnerDataById($uid);
823 $additional = ['uid:' . $uid => $uid];
824 $receivers = array_merge($receivers, $additional);
827 logger('Receivers: ' . json_encode($receivers), LOGGER_DEBUG);
829 $public = in_array(0, $receivers);
831 if (is_string($activity['object'])) {
832 $object_url = $activity['object'];
833 } elseif (!empty($activity['object']['id'])) {
834 $object_url = $activity['object']['id'];
836 logger('No object found', LOGGER_DEBUG);
840 // Fetch the content only on activities where this matters
841 if (in_array($activity['type'], ['Create', 'Update', 'Announce'])) {
842 $object_data = self::fetchObject($object_url, $activity['object']);
843 if (empty($object_data)) {
844 logger("Object data couldn't be processed", LOGGER_DEBUG);
847 } elseif ($activity['type'] == 'Accept') {
849 $object_data['object_type'] = self::processElement($activity, 'object', 'type');
850 $object_data['object'] = self::processElement($activity, 'object', 'actor');
851 } elseif ($activity['type'] == 'Undo') {
853 $object_data['object_type'] = self::processElement($activity, 'object', 'type');
854 $object_data['object'] = self::processElement($activity, 'object', 'object');
855 } elseif (in_array($activity['type'], ['Like', 'Dislike'])) {
856 // Create a mostly empty array out of the activity data (instead of the object).
857 // This way we later don't have to check for the existence of ech individual array element.
858 $object_data = self::processCommonData($activity);
859 $object_data['name'] = $activity['type'];
860 $object_data['author'] = $activity['actor'];
861 $object_data['object'] = $object_url;
862 } elseif ($activity['type'] == 'Follow') {
863 $object_data['id'] = $activity['id'];
864 $object_data['object'] = $object_url;
869 $object_data = self::addActivityFields($object_data, $activity);
871 $object_data['type'] = $activity['type'];
872 $object_data['owner'] = $actor;
873 $object_data['receiver'] = array_merge(defaults($object_data, 'receiver', []), $receivers);
878 private static function processActivity($activity, $body = '', $uid = null)
880 if (empty($activity['type'])) {
881 logger('Empty type', LOGGER_DEBUG);
885 if (empty($activity['object'])) {
886 logger('Empty object', LOGGER_DEBUG);
890 if (empty($activity['actor'])) {
891 logger('Empty actor', LOGGER_DEBUG);
897 // title, atomUri, context_id, statusnetConversationId
900 // context, location, signature;
902 logger('Processing activity: ' . $activity['type'], LOGGER_DEBUG);
904 $object_data = self::prepareObjectData($activity, $uid);
905 if (empty($object_data)) {
906 logger('No object data found', LOGGER_DEBUG);
910 switch ($activity['type']) {
913 self::createItem($object_data, $body);
917 self::likeItem($object_data, $body);
930 self::followUser($object_data);
934 if ($object_data['object_type'] == 'Follow') {
935 self::acceptFollowUser($object_data);
940 if ($object_data['object_type'] == 'Follow') {
941 self::undoFollowUser($object_data);
946 logger('Unknown activity: ' . $activity['type'], LOGGER_DEBUG);
951 private static function getReceivers($activity, $actor)
955 if (!empty($actor)) {
956 $data = self::fetchContent($actor);
957 $followers = defaults($data, 'followers', '');
959 logger('Actor: ' . $actor . ' - Followers: ' . $followers, LOGGER_DEBUG);
961 logger('Empty actor', LOGGER_DEBUG);
965 $elements = ['to', 'cc', 'bto', 'bcc'];
966 foreach ($elements as $element) {
967 if (empty($activity[$element])) {
971 // The receiver can be an arror or a string
972 if (is_string($activity[$element])) {
973 $activity[$element] = [$activity[$element]];
976 foreach ($activity[$element] as $receiver) {
977 if ($receiver == self::PUBLIC) {
978 $receivers['uid:0'] = 0;
981 if (($receiver == self::PUBLIC) && !empty($actor)) {
982 // This will most likely catch all OStatus connections to Mastodon
983 $condition = ['alias' => [$actor, normalise_link($actor)], 'rel' => [Contact::SHARING, Contact::FRIEND]];
984 $contacts = DBA::select('contact', ['uid'], $condition);
985 while ($contact = DBA::fetch($contacts)) {
986 if ($contact['uid'] != 0) {
987 $receivers['uid:' . $contact['uid']] = $contact['uid'];
990 DBA::close($contacts);
993 if (in_array($receiver, [$followers, self::PUBLIC]) && !empty($actor)) {
994 $condition = ['nurl' => normalise_link($actor), 'rel' => [Contact::SHARING, Contact::FRIEND],
995 'network' => Protocol::ACTIVITYPUB];
996 $contacts = DBA::select('contact', ['uid'], $condition);
997 while ($contact = DBA::fetch($contacts)) {
998 if ($contact['uid'] != 0) {
999 $receivers['uid:' . $contact['uid']] = $contact['uid'];
1002 DBA::close($contacts);
1006 $condition = ['self' => true, 'nurl' => normalise_link($receiver)];
1007 $contact = DBA::selectFirst('contact', ['uid'], $condition);
1008 if (!DBA::isResult($contact)) {
1011 $receivers['uid:' . $contact['uid']] = $contact['uid'];
1017 private static function addActivityFields($object_data, $activity)
1019 if (!empty($activity['published']) && empty($object_data['published'])) {
1020 $object_data['published'] = $activity['published'];
1023 if (!empty($activity['updated']) && empty($object_data['updated'])) {
1024 $object_data['updated'] = $activity['updated'];
1027 if (!empty($activity['inReplyTo']) && empty($object_data['parent-uri'])) {
1028 $object_data['parent-uri'] = self::processElement($activity, 'inReplyTo', 'id');
1031 if (!empty($activity['instrument'])) {
1032 $object_data['service'] = self::processElement($activity, 'instrument', 'name', 'type', 'Service');
1034 return $object_data;
1037 private static function fetchObject($object_url, $object = [], $public = true)
1040 $data = self::fetchContent($object_url);
1042 logger('Empty content for ' . $object_url . ', check if content is available locally.', LOGGER_DEBUG);
1043 $data = $object_url;
1047 logger('Using original object for url ' . $object_url, LOGGER_DEBUG);
1051 if (is_string($data)) {
1052 $item = Item::selectFirst([], ['uri' => $data]);
1053 if (!DBA::isResult($item)) {
1054 logger('Object with url ' . $data . ' was not found locally.', LOGGER_DEBUG);
1057 logger('Using already stored item for url ' . $object_url, LOGGER_DEBUG);
1058 $data = self::createNote($item);
1061 if (empty($data['type'])) {
1062 logger('Empty type', LOGGER_DEBUG);
1065 $type = $data['type'];
1066 logger('Type ' . $type, LOGGER_DEBUG);
1069 if (in_array($type, ['Note', 'Article', 'Video'])) {
1070 $common = self::processCommonData($data);
1075 return array_merge($common, self::processNote($data));
1077 return array_merge($common, self::processArticle($data));
1079 return array_merge($common, self::processVideo($data));
1082 if (empty($data['object'])) {
1085 return self::fetchObject($data['object']);
1092 logger('Unknown object type: ' . $data['type'], LOGGER_DEBUG);
1097 private static function processCommonData(&$object)
1099 if (empty($object['id'])) {
1104 $object_data['type'] = $object['type'];
1105 $object_data['uri'] = $object['id'];
1107 if (!empty($object['inReplyTo'])) {
1108 $object_data['reply-to-uri'] = self::processElement($object, 'inReplyTo', 'id');
1110 $object_data['reply-to-uri'] = $object_data['uri'];
1113 $object_data['published'] = defaults($object, 'published', null);
1114 $object_data['updated'] = defaults($object, 'updated', $object_data['published']);
1116 if (empty($object_data['published']) && !empty($object_data['updated'])) {
1117 $object_data['published'] = $object_data['updated'];
1120 $object_data['uuid'] = defaults($object, 'uuid', null);
1121 $object_data['owner'] = $object_data['author'] = self::processElement($object, 'attributedTo', 'id');
1122 $object_data['context'] = defaults($object, 'context', null);
1123 $object_data['conversation'] = defaults($object, 'conversation', null);
1124 $object_data['sensitive'] = defaults($object, 'sensitive', null);
1125 $object_data['name'] = defaults($object, 'title', null);
1126 $object_data['name'] = defaults($object, 'name', $object_data['name']);
1127 $object_data['summary'] = defaults($object, 'summary', null);
1128 $object_data['content'] = defaults($object, 'content', null);
1129 $object_data['source'] = defaults($object, 'source', null);
1130 $object_data['location'] = self::processElement($object, 'location', 'name', 'type', 'Place');
1131 $object_data['attachments'] = defaults($object, 'attachment', null);
1132 $object_data['tags'] = defaults($object, 'tag', null);
1133 $object_data['service'] = self::processElement($object, 'instrument', 'name', 'type', 'Service');
1134 $object_data['alternate-url'] = self::processElement($object, 'url', 'href');
1135 $object_data['receiver'] = self::getReceivers($object, $object_data['owner']);
1138 // @context, type, actor, signature, mediaType, duration, replies, icon
1140 // Also missing: (Defined in the standard, but currently unused)
1141 // audience, preview, endTime, startTime, generator, image
1143 return $object_data;
1146 private static function processNote($object)
1151 // emoji, atomUri, inReplyToAtomUri
1154 // contentMap, announcement_count, announcements, context_id, likes, like_count
1155 // inReplyToStatusId, shares, quoteUrl, statusnetConversationId
1157 return $object_data;
1160 private static function processArticle($object)
1164 return $object_data;
1167 private static function processVideo($object)
1172 // category, licence, language, commentsEnabled
1175 // views, waitTranscoding, state, support, subtitleLanguage
1176 // likes, dislikes, shares, comments
1178 return $object_data;
1181 private static function processElement($array, $element, $key, $type = null, $type_value = null)
1183 if (empty($array)) {
1187 if (empty($array[$element])) {
1191 if (is_string($array[$element])) {
1192 return $array[$element];
1195 if (is_null($type_value)) {
1196 if (!empty($array[$element][$key])) {
1197 return $array[$element][$key];
1200 if (!empty($array[$element][0][$key])) {
1201 return $array[$element][0][$key];
1207 if (!empty($array[$element][$key]) && !empty($array[$element][$type]) && ($array[$element][$type] == $type_value)) {
1208 return $array[$element][$key];
1211 /// @todo Add array search
1216 private static function convertMentions($body)
1218 $URLSearchString = "^\[\]";
1219 $body = preg_replace("/\[url\=([$URLSearchString]*)\]([#@!])(.*?)\[\/url\]/ism", '$2[url=$1]$3[/url]', $body);
1224 private static function constructTagList($tags, $sensitive)
1231 foreach ($tags as $tag) {
1232 if (in_array($tag['type'], ['Mention', 'Hashtag'])) {
1233 if (!empty($tag_text)) {
1237 if (empty($tag['href'])) {
1242 $tag_text .= substr($tag['name'], 0, 1) . '[url=' . $tag['href'] . ']' . substr($tag['name'], 1) . '[/url]';
1246 /// @todo add nsfw for $sensitive
1251 private static function constructAttachList($attachments, $item)
1253 if (empty($attachments)) {
1257 foreach ($attachments as $attach) {
1258 $filetype = strtolower(substr($attach['mediaType'], 0, strpos($attach['mediaType'], '/')));
1259 if ($filetype == 'image') {
1260 $item['body'] .= "\n[img]".$attach['url'].'[/img]';
1262 if (!empty($item["attach"])) {
1263 $item["attach"] .= ',';
1265 $item["attach"] = '';
1267 if (!isset($attach['length'])) {
1268 $attach['length'] = "0";
1270 $item["attach"] .= '[attach]href="'.$attach['url'].'" length="'.$attach['length'].'" type="'.$attach['mediaType'].'" title="'.defaults($attach, 'name', '').'"[/attach]';
1277 private static function createItem($activity, $body)
1280 $item['verb'] = ACTIVITY_POST;
1281 $item['parent-uri'] = $activity['reply-to-uri'];
1283 if ($activity['reply-to-uri'] == $activity['uri']) {
1284 $item['gravity'] = GRAVITY_PARENT;
1285 $item['object-type'] = ACTIVITY_OBJ_NOTE;
1287 $item['gravity'] = GRAVITY_COMMENT;
1288 $item['object-type'] = ACTIVITY_OBJ_COMMENT;
1291 if (($activity['uri'] != $activity['reply-to-uri']) && !Item::exists(['uri' => $activity['reply-to-uri']])) {
1292 logger('Parent ' . $activity['reply-to-uri'] . ' not found. Try to refetch it.');
1293 self::fetchMissingActivity($activity['reply-to-uri'], $activity);
1296 self::postItem($activity, $item, $body);
1299 private static function likeItem($activity, $body)
1302 $item['verb'] = ACTIVITY_LIKE;
1303 $item['parent-uri'] = $activity['object'];
1304 $item['gravity'] = GRAVITY_ACTIVITY;
1305 $item['object-type'] = ACTIVITY_OBJ_NOTE;
1307 self::postItem($activity, $item, $body);
1310 private static function postItem($activity, $item, $body)
1312 /// @todo What to do with $activity['context']?
1314 $item['network'] = Protocol::ACTIVITYPUB;
1315 $item['private'] = !in_array(0, $activity['receiver']);
1316 $item['author-id'] = Contact::getIdForURL($activity['author'], 0, true);
1317 $item['owner-id'] = Contact::getIdForURL($activity['owner'], 0, true);
1318 $item['uri'] = $activity['uri'];
1319 $item['created'] = $activity['published'];
1320 $item['edited'] = $activity['updated'];
1321 $item['guid'] = $activity['uuid'];
1322 $item['title'] = HTML::toBBCode($activity['name']);
1323 $item['content-warning'] = HTML::toBBCode($activity['summary']);
1324 $item['body'] = self::convertMentions(HTML::toBBCode($activity['content']));
1325 $item['location'] = $activity['location'];
1326 $item['tag'] = self::constructTagList($activity['tags'], $activity['sensitive']);
1327 $item['app'] = $activity['service'];
1328 $item['plink'] = defaults($activity, 'alternate-url', $item['uri']);
1330 $item = self::constructAttachList($activity['attachments'], $item);
1332 $source = self::processElement($activity, 'source', 'content', 'mediaType', 'text/bbcode');
1333 if (!empty($source)) {
1334 $item['body'] = $source;
1337 $item['protocol'] = Conversation::PARCEL_ACTIVITYPUB;
1338 $item['source'] = $body;
1339 $item['conversation-uri'] = $activity['conversation'];
1341 foreach ($activity['receiver'] as $receiver) {
1342 $item['uid'] = $receiver;
1343 $item['contact-id'] = Contact::getIdForURL($activity['author'], $receiver, true);
1345 if (($receiver != 0) && empty($item['contact-id'])) {
1346 $item['contact-id'] = Contact::getIdForURL($activity['author'], 0, true);
1349 $item_id = Item::insert($item);
1350 logger('Storing for user ' . $item['uid'] . ': ' . $item_id);
1354 private static function fetchMissingActivity($url, $child)
1356 $object = ActivityPub::fetchContent($url);
1357 if (empty($object)) {
1358 logger('Activity ' . $url . ' was not fetchable, aborting.');
1363 $activity['@context'] = $object['@context'];
1364 unset($object['@context']);
1365 $activity['id'] = $object['id'];
1366 $activity['to'] = defaults($object, 'to', []);
1367 $activity['cc'] = defaults($object, 'cc', []);
1368 $activity['actor'] = $activity['author'];
1369 $activity['object'] = $object;
1370 $activity['published'] = $object['published'];
1371 $activity['type'] = 'Create';
1372 self::processActivity($activity);
1373 logger('Activity ' . $url . ' had been fetched and processed.');
1376 private static function getUserOfObject($object)
1378 $self = DBA::selectFirst('contact', ['uid'], ['nurl' => normalise_link($object), 'self' => true]);
1379 if (!DBA::isResult($self)) {
1382 return $self['uid'];
1386 private static function followUser($activity)
1388 $uid = self::getUserOfObject($activity['object']);
1393 $owner = User::getOwnerDataById($uid);
1395 $cid = Contact::getIdForURL($activity['owner'], $uid);
1397 $contact = DBA::selectFirst('contact', [], ['id' => $cid]);
1402 $item = ['author-id' => Contact::getIdForURL($activity['owner']),
1403 'author-link' => $activity['owner']];
1405 Contact::addRelationship($owner, $contact, $item);
1406 $cid = Contact::getIdForURL($activity['owner'], $uid);
1411 $contact = DBA::selectFirst('contact', ['network'], ['id' => $cid]);
1412 if ($contact['network'] != Protocol::ACTIVITYPUB) {
1413 Contact::updateFromProbe($cid, Protocol::ACTIVITYPUB);
1416 DBA::update('contact', ['hub-verify' => $activity['id']], ['id' => $cid]);
1417 logger('Follow user ' . $uid . ' from contact ' . $cid . ' with id ' . $activity['id']);
1420 private static function acceptFollowUser($activity)
1422 $uid = self::getUserOfObject($activity['object']);
1427 $owner = User::getOwnerDataById($uid);
1429 $cid = Contact::getIdForURL($activity['owner'], $uid);
1431 logger('No contact found for ' . $activity['owner'], LOGGER_DEBUG);
1435 $fields = ['pending' => false];
1437 $contact = DBA::selectFirst('contact', ['rel'], ['id' => $cid]);
1438 if ($contact['rel'] == Contact::FOLLOWER) {
1439 $fields['rel'] = Contact::FRIEND;
1442 $condition = ['id' => $cid];
1443 DBA::update('contact', $fields, $condition);
1444 logger('Accept contact request from contact ' . $cid . ' for user ' . $uid, LOGGER_DEBUG);
1447 private static function undoFollowUser($activity)
1449 $uid = self::getUserOfObject($activity['object']);
1454 $owner = User::getOwnerDataById($uid);
1456 $cid = Contact::getIdForURL($activity['owner'], $uid);
1458 logger('No contact found for ' . $activity['owner'], LOGGER_DEBUG);
1462 $contact = DBA::selectFirst('contact', [], ['id' => $cid]);
1463 if (!DBA::isResult($contact)) {
1467 Contact::removeFollower($owner, $contact);
1468 logger('Undo following request from contact ' . $cid . ' for user ' . $uid, LOGGER_DEBUG);