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\Util\JsonLD;
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 = self::fetchprofile($term['url']);
171 if (!empty($profile)) {
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 = self::fetchprofile($term['url']);
225 if (!empty($profile)) {
226 $target = defaults($profile, 'sharedinbox', $profile['inbox']);
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 = self::fetchprofile($contact['url']);
243 if (!empty($profile['network'])) {
244 $target = defaults($profile, 'sharedinbox', $profile['inbox']);
245 $inboxes[$target] = $target;
250 foreach ($receiver_list as $receiver) {
251 $contact = DBA::selectFirst('contact', ['url'], ['id' => $receiver, 'network' => Protocol::ACTIVITYPUB]);
252 $profile = self::fetchprofile($contact['url']);
253 if (!empty($profile['network'])) {
254 $target = defaults($profile, 'sharedinbox', $profile['inbox']);
255 $inboxes[$target] = $target;
260 $profile = self::fetchprofile($item['author-link']);
261 if (!empty($profile['sharedinbox'])) {
262 unset($inboxes[$profile['sharedinbox']]);
265 if (!empty($profile['inbox'])) {
266 unset($inboxes[$profile['inbox']]);
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 = self::fetchprofile($target);
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['inbox'], $uid);
407 public static function transmitContactAccept($target, $id, $uid)
409 $profile = self::fetchprofile($target);
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['inbox'], $uid);
425 public static function transmitContactReject($target, $id, $uid)
427 $profile = self::fetchprofile($target);
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['inbox'], $uid);
443 public static function transmitContactUndo($target, $uid)
445 $profile = self::fetchprofile($target);
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['inbox'], $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 = JsonLD::fetchElement($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 = self::fetchprofile($url);
620 if (!empty($profile)) {
621 return $profile['pubkey'];
622 } elseif ($url != $actor) {
623 $profile = self::fetchprofile($actor);
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]));
666 public static function fetchprofile($url, $update = false)
673 $apcontact = DBA::selectFirst('apcontact', [], ['url' => $url]);
674 if (DBA::isResult($apcontact)) {
678 $apcontact = DBA::selectFirst('apcontact', [], ['alias' => $url]);
679 if (DBA::isResult($apcontact)) {
683 $apcontact = DBA::selectFirst('apcontact', [], ['addr' => $url]);
684 if (DBA::isResult($apcontact)) {
689 if (empty(parse_url($url, PHP_URL_SCHEME))) {
690 $url = self::addrToUrl($url);
696 $data = self::fetchContent($url);
698 if (empty($data) || empty($data['id']) || empty($data['inbox'])) {
703 $apcontact['url'] = $data['id'];
704 $apcontact['uuid'] = defaults($data, 'uuid', null);
705 $apcontact['type'] = defaults($data, 'type', null);
706 $apcontact['following'] = defaults($data, 'following', null);
707 $apcontact['followers'] = defaults($data, 'followers', null);
708 $apcontact['inbox'] = defaults($data, 'inbox', null);
709 $apcontact['outbox'] = defaults($data, 'outbox', null);
710 $apcontact['sharedinbox'] = JsonLD::fetchElement($data, 'endpoints', 'sharedInbox');
711 $apcontact['nick'] = defaults($data, 'preferredUsername', null);
712 $apcontact['name'] = defaults($data, 'name', $apcontact['nick']);
713 $apcontact['about'] = defaults($data, 'summary', '');
714 $apcontact['photo'] = JsonLD::fetchElement($data, 'icon', 'url');
715 $apcontact['alias'] = JsonLD::fetchElement($data, 'url', 'href');
717 $parts = parse_url($apcontact['url']);
718 unset($parts['scheme']);
719 unset($parts['path']);
720 $apcontact['addr'] = $apcontact['nick'] . '@' . str_replace('//', '', Network::unparseURL($parts));
722 $apcontact['pubkey'] = trim(JsonLD::fetchElement($data, 'publicKey', 'publicKeyPem'));
725 // manuallyApprovesFollowers
728 // @context, tag, attachment, image, nomadicLocations, signature, following, followers, featured, movedTo, liked
730 // Unhandled from Misskey
731 // sharedInbox, isCat
733 // Unhandled from Kroeg
734 // kroeg:blocks, updated
736 // Check if the address is resolvable
737 if (self::addrToUrl($apcontact['addr']) == $apcontact['url']) {
738 $parts = parse_url($apcontact['url']);
739 unset($parts['path']);
740 $apcontact['baseurl'] = Network::unparseURL($parts);
742 $apcontact['addr'] = null;
745 if ($apcontact['url'] == $apcontact['alias']) {
746 $apcontact['alias'] = null;
749 $apcontact['updated'] = DateTimeFormat::utcNow();
751 DBA::update('apcontact', $apcontact, ['url' => $url], true);
757 * Fetches a profile from the given url into an array that is compatible to Probe::uri
759 * @param string $url profile url
762 public static function probeProfile($url)
764 $apcontact = self::fetchprofile($url, true);
765 if (empty($apcontact)) {
769 $profile = ['network' => Protocol::ACTIVITYPUB];
770 $profile['nick'] = $apcontact['nick'];
771 $profile['name'] = $apcontact['name'];
772 $profile['guid'] = $apcontact['uuid'];
773 $profile['url'] = $apcontact['url'];
774 $profile['addr'] = $apcontact['addr'];
775 $profile['alias'] = $apcontact['alias'];
776 $profile['photo'] = $apcontact['photo'];
777 // $profile['community']
778 // $profile['keywords']
779 // $profile['location']
780 $profile['about'] = $apcontact['about'];
781 $profile['batch'] = $apcontact['sharedinbox'];
782 $profile['notify'] = $apcontact['inbox'];
783 $profile['poll'] = $apcontact['outbox'];
784 $profile['pubkey'] = $apcontact['pubkey'];
785 $profile['baseurl'] = $apcontact['baseurl'];
787 // Remove all "null" fields
788 foreach ($profile as $field => $content) {
789 if (is_null($content)) {
790 unset($profile[$field]);
797 public static function processInbox($body, $header, $uid)
799 logger('Incoming message for user ' . $uid, LOGGER_DEBUG);
801 if (!self::verifySignature($body, $header)) {
802 logger('Invalid signature, message will be discarded.', LOGGER_DEBUG);
806 $activity = json_decode($body, true);
808 if (!is_array($activity)) {
809 logger('Invalid body.', LOGGER_DEBUG);
813 self::processActivity($activity, $body, $uid);
816 public static function fetchOutbox($url)
818 $data = self::fetchContent($url);
823 if (!empty($data['orderedItems'])) {
824 $items = $data['orderedItems'];
825 } elseif (!empty($data['first']['orderedItems'])) {
826 $items = $data['first']['orderedItems'];
827 } elseif (!empty($data['first'])) {
828 self::fetchOutbox($data['first']);
834 foreach ($items as $activity) {
835 self::processActivity($activity);
839 private static function prepareObjectData($activity, $uid)
841 $actor = JsonLD::fetchElement($activity, 'actor', 'id');
843 logger('Empty actor', LOGGER_DEBUG);
847 // Fetch all receivers from to, cc, bto and bcc
848 $receivers = self::getReceivers($activity, $actor);
850 // When it is a delivery to a personal inbox we add that user to the receivers
852 $owner = User::getOwnerDataById($uid);
853 $additional = ['uid:' . $uid => $uid];
854 $receivers = array_merge($receivers, $additional);
857 logger('Receivers: ' . json_encode($receivers), LOGGER_DEBUG);
859 $public = in_array(0, $receivers);
861 if (is_string($activity['object'])) {
862 $object_url = $activity['object'];
863 } elseif (!empty($activity['object']['id'])) {
864 $object_url = $activity['object']['id'];
866 logger('No object found', LOGGER_DEBUG);
870 // Fetch the content only on activities where this matters
871 if (in_array($activity['type'], ['Create', 'Update', 'Announce'])) {
872 $object_data = self::fetchObject($object_url, $activity['object']);
873 if (empty($object_data)) {
874 logger("Object data couldn't be processed", LOGGER_DEBUG);
877 } elseif ($activity['type'] == 'Accept') {
879 $object_data['object_type'] = JsonLD::fetchElement($activity, 'object', 'type');
880 $object_data['object'] = JsonLD::fetchElement($activity, 'object', 'actor');
881 } elseif ($activity['type'] == 'Undo') {
883 $object_data['object_type'] = JsonLD::fetchElement($activity, 'object', 'type');
884 $object_data['object'] = JsonLD::fetchElement($activity, 'object', 'object');
885 } elseif (in_array($activity['type'], ['Like', 'Dislike'])) {
886 // Create a mostly empty array out of the activity data (instead of the object).
887 // This way we later don't have to check for the existence of ech individual array element.
888 $object_data = self::processCommonData($activity);
889 $object_data['name'] = $activity['type'];
890 $object_data['author'] = $activity['actor'];
891 $object_data['object'] = $object_url;
892 } elseif ($activity['type'] == 'Follow') {
893 $object_data['id'] = $activity['id'];
894 $object_data['object'] = $object_url;
899 $object_data = self::addActivityFields($object_data, $activity);
901 $object_data['type'] = $activity['type'];
902 $object_data['owner'] = $actor;
903 $object_data['receiver'] = array_merge(defaults($object_data, 'receiver', []), $receivers);
908 private static function processActivity($activity, $body = '', $uid = null)
910 if (empty($activity['type'])) {
911 logger('Empty type', LOGGER_DEBUG);
915 if (empty($activity['object'])) {
916 logger('Empty object', LOGGER_DEBUG);
920 if (empty($activity['actor'])) {
921 logger('Empty actor', LOGGER_DEBUG);
927 // title, atomUri, context_id, statusnetConversationId
930 // context, location, signature;
932 logger('Processing activity: ' . $activity['type'], LOGGER_DEBUG);
934 $object_data = self::prepareObjectData($activity, $uid);
935 if (empty($object_data)) {
936 logger('No object data found', LOGGER_DEBUG);
940 switch ($activity['type']) {
943 self::createItem($object_data, $body);
947 self::likeItem($object_data, $body);
960 self::followUser($object_data);
964 if ($object_data['object_type'] == 'Follow') {
965 self::acceptFollowUser($object_data);
970 if ($object_data['object_type'] == 'Follow') {
971 self::undoFollowUser($object_data);
976 logger('Unknown activity: ' . $activity['type'], LOGGER_DEBUG);
981 private static function getReceivers($activity, $actor)
985 if (!empty($actor)) {
986 $profile = self::fetchprofile($actor);
987 $followers = defaults($profile, 'followers', '');
989 logger('Actor: ' . $actor . ' - Followers: ' . $followers, LOGGER_DEBUG);
991 logger('Empty actor', LOGGER_DEBUG);
995 $elements = ['to', 'cc', 'bto', 'bcc'];
996 foreach ($elements as $element) {
997 if (empty($activity[$element])) {
1001 // The receiver can be an arror or a string
1002 if (is_string($activity[$element])) {
1003 $activity[$element] = [$activity[$element]];
1006 foreach ($activity[$element] as $receiver) {
1007 if ($receiver == self::PUBLIC) {
1008 $receivers['uid:0'] = 0;
1011 if (($receiver == self::PUBLIC) && !empty($actor)) {
1012 // This will most likely catch all OStatus connections to Mastodon
1013 $condition = ['alias' => [$actor, normalise_link($actor)], 'rel' => [Contact::SHARING, Contact::FRIEND]];
1014 $contacts = DBA::select('contact', ['uid'], $condition);
1015 while ($contact = DBA::fetch($contacts)) {
1016 if ($contact['uid'] != 0) {
1017 $receivers['uid:' . $contact['uid']] = $contact['uid'];
1020 DBA::close($contacts);
1023 if (in_array($receiver, [$followers, self::PUBLIC]) && !empty($actor)) {
1024 $condition = ['nurl' => normalise_link($actor), 'rel' => [Contact::SHARING, Contact::FRIEND],
1025 'network' => Protocol::ACTIVITYPUB];
1026 $contacts = DBA::select('contact', ['uid'], $condition);
1027 while ($contact = DBA::fetch($contacts)) {
1028 if ($contact['uid'] != 0) {
1029 $receivers['uid:' . $contact['uid']] = $contact['uid'];
1032 DBA::close($contacts);
1036 $condition = ['self' => true, 'nurl' => normalise_link($receiver)];
1037 $contact = DBA::selectFirst('contact', ['uid'], $condition);
1038 if (!DBA::isResult($contact)) {
1041 $receivers['uid:' . $contact['uid']] = $contact['uid'];
1047 private static function addActivityFields($object_data, $activity)
1049 if (!empty($activity['published']) && empty($object_data['published'])) {
1050 $object_data['published'] = $activity['published'];
1053 if (!empty($activity['updated']) && empty($object_data['updated'])) {
1054 $object_data['updated'] = $activity['updated'];
1057 if (!empty($activity['inReplyTo']) && empty($object_data['parent-uri'])) {
1058 $object_data['parent-uri'] = JsonLD::fetchElement($activity, 'inReplyTo', 'id');
1061 if (!empty($activity['instrument'])) {
1062 $object_data['service'] = JsonLD::fetchElement($activity, 'instrument', 'name', 'type', 'Service');
1064 return $object_data;
1067 private static function fetchObject($object_url, $object = [], $public = true)
1070 $data = self::fetchContent($object_url);
1072 logger('Empty content for ' . $object_url . ', check if content is available locally.', LOGGER_DEBUG);
1073 $data = $object_url;
1077 logger('Using original object for url ' . $object_url, LOGGER_DEBUG);
1081 if (is_string($data)) {
1082 $item = Item::selectFirst([], ['uri' => $data]);
1083 if (!DBA::isResult($item)) {
1084 logger('Object with url ' . $data . ' was not found locally.', LOGGER_DEBUG);
1087 logger('Using already stored item for url ' . $object_url, LOGGER_DEBUG);
1088 $data = self::createNote($item);
1091 if (empty($data['type'])) {
1092 logger('Empty type', LOGGER_DEBUG);
1095 $type = $data['type'];
1096 logger('Type ' . $type, LOGGER_DEBUG);
1099 if (in_array($type, ['Note', 'Article', 'Video'])) {
1100 $common = self::processCommonData($data);
1105 return array_merge($common, self::processNote($data));
1107 return array_merge($common, self::processArticle($data));
1109 return array_merge($common, self::processVideo($data));
1112 if (empty($data['object'])) {
1115 return self::fetchObject($data['object']);
1122 logger('Unknown object type: ' . $data['type'], LOGGER_DEBUG);
1127 private static function processCommonData(&$object)
1129 if (empty($object['id'])) {
1134 $object_data['type'] = $object['type'];
1135 $object_data['uri'] = $object['id'];
1137 if (!empty($object['inReplyTo'])) {
1138 $object_data['reply-to-uri'] = JsonLD::fetchElement($object, 'inReplyTo', 'id');
1140 $object_data['reply-to-uri'] = $object_data['uri'];
1143 $object_data['published'] = defaults($object, 'published', null);
1144 $object_data['updated'] = defaults($object, 'updated', $object_data['published']);
1146 if (empty($object_data['published']) && !empty($object_data['updated'])) {
1147 $object_data['published'] = $object_data['updated'];
1150 $object_data['uuid'] = defaults($object, 'uuid', null);
1151 $object_data['owner'] = $object_data['author'] = JsonLD::fetchElement($object, 'attributedTo', 'id');
1152 $object_data['context'] = defaults($object, 'context', null);
1153 $object_data['conversation'] = defaults($object, 'conversation', null);
1154 $object_data['sensitive'] = defaults($object, 'sensitive', null);
1155 $object_data['name'] = defaults($object, 'title', null);
1156 $object_data['name'] = defaults($object, 'name', $object_data['name']);
1157 $object_data['summary'] = defaults($object, 'summary', null);
1158 $object_data['content'] = defaults($object, 'content', null);
1159 $object_data['source'] = defaults($object, 'source', null);
1160 $object_data['location'] = JsonLD::fetchElement($object, 'location', 'name', 'type', 'Place');
1161 $object_data['attachments'] = defaults($object, 'attachment', null);
1162 $object_data['tags'] = defaults($object, 'tag', null);
1163 $object_data['service'] = JsonLD::fetchElement($object, 'instrument', 'name', 'type', 'Service');
1164 $object_data['alternate-url'] = JsonLD::fetchElement($object, 'url', 'href');
1165 $object_data['receiver'] = self::getReceivers($object, $object_data['owner']);
1168 // @context, type, actor, signature, mediaType, duration, replies, icon
1170 // Also missing: (Defined in the standard, but currently unused)
1171 // audience, preview, endTime, startTime, generator, image
1173 return $object_data;
1176 private static function processNote($object)
1181 // emoji, atomUri, inReplyToAtomUri
1184 // contentMap, announcement_count, announcements, context_id, likes, like_count
1185 // inReplyToStatusId, shares, quoteUrl, statusnetConversationId
1187 return $object_data;
1190 private static function processArticle($object)
1194 return $object_data;
1197 private static function processVideo($object)
1202 // category, licence, language, commentsEnabled
1205 // views, waitTranscoding, state, support, subtitleLanguage
1206 // likes, dislikes, shares, comments
1208 return $object_data;
1211 private static function convertMentions($body)
1213 $URLSearchString = "^\[\]";
1214 $body = preg_replace("/\[url\=([$URLSearchString]*)\]([#@!])(.*?)\[\/url\]/ism", '$2[url=$1]$3[/url]', $body);
1219 private static function constructTagList($tags, $sensitive)
1226 foreach ($tags as $tag) {
1227 if (in_array($tag['type'], ['Mention', 'Hashtag'])) {
1228 if (!empty($tag_text)) {
1232 if (empty($tag['href'])) {
1237 $tag_text .= substr($tag['name'], 0, 1) . '[url=' . $tag['href'] . ']' . substr($tag['name'], 1) . '[/url]';
1241 /// @todo add nsfw for $sensitive
1246 private static function constructAttachList($attachments, $item)
1248 if (empty($attachments)) {
1252 foreach ($attachments as $attach) {
1253 $filetype = strtolower(substr($attach['mediaType'], 0, strpos($attach['mediaType'], '/')));
1254 if ($filetype == 'image') {
1255 $item['body'] .= "\n[img]".$attach['url'].'[/img]';
1257 if (!empty($item["attach"])) {
1258 $item["attach"] .= ',';
1260 $item["attach"] = '';
1262 if (!isset($attach['length'])) {
1263 $attach['length'] = "0";
1265 $item["attach"] .= '[attach]href="'.$attach['url'].'" length="'.$attach['length'].'" type="'.$attach['mediaType'].'" title="'.defaults($attach, 'name', '').'"[/attach]';
1272 private static function createItem($activity, $body)
1275 $item['verb'] = ACTIVITY_POST;
1276 $item['parent-uri'] = $activity['reply-to-uri'];
1278 if ($activity['reply-to-uri'] == $activity['uri']) {
1279 $item['gravity'] = GRAVITY_PARENT;
1280 $item['object-type'] = ACTIVITY_OBJ_NOTE;
1282 $item['gravity'] = GRAVITY_COMMENT;
1283 $item['object-type'] = ACTIVITY_OBJ_COMMENT;
1286 if (($activity['uri'] != $activity['reply-to-uri']) && !Item::exists(['uri' => $activity['reply-to-uri']])) {
1287 logger('Parent ' . $activity['reply-to-uri'] . ' not found. Try to refetch it.');
1288 self::fetchMissingActivity($activity['reply-to-uri'], $activity);
1291 self::postItem($activity, $item, $body);
1294 private static function likeItem($activity, $body)
1297 $item['verb'] = ACTIVITY_LIKE;
1298 $item['parent-uri'] = $activity['object'];
1299 $item['gravity'] = GRAVITY_ACTIVITY;
1300 $item['object-type'] = ACTIVITY_OBJ_NOTE;
1302 self::postItem($activity, $item, $body);
1305 private static function postItem($activity, $item, $body)
1307 /// @todo What to do with $activity['context']?
1309 $item['network'] = Protocol::ACTIVITYPUB;
1310 $item['private'] = !in_array(0, $activity['receiver']);
1311 $item['author-id'] = Contact::getIdForURL($activity['author'], 0, true);
1312 $item['owner-id'] = Contact::getIdForURL($activity['owner'], 0, true);
1313 $item['uri'] = $activity['uri'];
1314 $item['created'] = $activity['published'];
1315 $item['edited'] = $activity['updated'];
1316 $item['guid'] = $activity['uuid'];
1317 $item['title'] = HTML::toBBCode($activity['name']);
1318 $item['content-warning'] = HTML::toBBCode($activity['summary']);
1319 $item['body'] = self::convertMentions(HTML::toBBCode($activity['content']));
1320 $item['location'] = $activity['location'];
1321 $item['tag'] = self::constructTagList($activity['tags'], $activity['sensitive']);
1322 $item['app'] = $activity['service'];
1323 $item['plink'] = defaults($activity, 'alternate-url', $item['uri']);
1325 $item = self::constructAttachList($activity['attachments'], $item);
1327 $source = JsonLD::fetchElement($activity, 'source', 'content', 'mediaType', 'text/bbcode');
1328 if (!empty($source)) {
1329 $item['body'] = $source;
1332 $item['protocol'] = Conversation::PARCEL_ACTIVITYPUB;
1333 $item['source'] = $body;
1334 $item['conversation-uri'] = $activity['conversation'];
1336 foreach ($activity['receiver'] as $receiver) {
1337 $item['uid'] = $receiver;
1338 $item['contact-id'] = Contact::getIdForURL($activity['author'], $receiver, true);
1340 if (($receiver != 0) && empty($item['contact-id'])) {
1341 $item['contact-id'] = Contact::getIdForURL($activity['author'], 0, true);
1344 $item_id = Item::insert($item);
1345 logger('Storing for user ' . $item['uid'] . ': ' . $item_id);
1349 private static function fetchMissingActivity($url, $child)
1351 $object = ActivityPub::fetchContent($url);
1352 if (empty($object)) {
1353 logger('Activity ' . $url . ' was not fetchable, aborting.');
1358 $activity['@context'] = $object['@context'];
1359 unset($object['@context']);
1360 $activity['id'] = $object['id'];
1361 $activity['to'] = defaults($object, 'to', []);
1362 $activity['cc'] = defaults($object, 'cc', []);
1363 $activity['actor'] = $child['author'];
1364 $activity['object'] = $object;
1365 $activity['published'] = $object['published'];
1366 $activity['type'] = 'Create';
1367 self::processActivity($activity);
1368 logger('Activity ' . $url . ' had been fetched and processed.');
1371 private static function getUserOfObject($object)
1373 $self = DBA::selectFirst('contact', ['uid'], ['nurl' => normalise_link($object), 'self' => true]);
1374 if (!DBA::isResult($self)) {
1377 return $self['uid'];
1381 private static function followUser($activity)
1383 $uid = self::getUserOfObject($activity['object']);
1388 $owner = User::getOwnerDataById($uid);
1390 $cid = Contact::getIdForURL($activity['owner'], $uid);
1392 $contact = DBA::selectFirst('contact', [], ['id' => $cid]);
1397 $item = ['author-id' => Contact::getIdForURL($activity['owner']),
1398 'author-link' => $activity['owner']];
1400 Contact::addRelationship($owner, $contact, $item);
1401 $cid = Contact::getIdForURL($activity['owner'], $uid);
1406 $contact = DBA::selectFirst('contact', ['network'], ['id' => $cid]);
1407 if ($contact['network'] != Protocol::ACTIVITYPUB) {
1408 Contact::updateFromProbe($cid, Protocol::ACTIVITYPUB);
1411 DBA::update('contact', ['hub-verify' => $activity['id']], ['id' => $cid]);
1412 logger('Follow user ' . $uid . ' from contact ' . $cid . ' with id ' . $activity['id']);
1415 private static function acceptFollowUser($activity)
1417 $uid = self::getUserOfObject($activity['object']);
1422 $owner = User::getOwnerDataById($uid);
1424 $cid = Contact::getIdForURL($activity['owner'], $uid);
1426 logger('No contact found for ' . $activity['owner'], LOGGER_DEBUG);
1430 $fields = ['pending' => false];
1432 $contact = DBA::selectFirst('contact', ['rel'], ['id' => $cid]);
1433 if ($contact['rel'] == Contact::FOLLOWER) {
1434 $fields['rel'] = Contact::FRIEND;
1437 $condition = ['id' => $cid];
1438 DBA::update('contact', $fields, $condition);
1439 logger('Accept contact request from contact ' . $cid . ' for user ' . $uid, LOGGER_DEBUG);
1442 private static function undoFollowUser($activity)
1444 $uid = self::getUserOfObject($activity['object']);
1449 $owner = User::getOwnerDataById($uid);
1451 $cid = Contact::getIdForURL($activity['owner'], $uid);
1453 logger('No contact found for ' . $activity['owner'], LOGGER_DEBUG);
1457 $contact = DBA::selectFirst('contact', [], ['id' => $cid]);
1458 if (!DBA::isResult($contact)) {
1462 Contact::removeFollower($owner, $contact);
1463 logger('Undo following request from contact ' . $cid . ' for user ' . $uid, LOGGER_DEBUG);