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;
24 * @brief ActivityPub Protocol class
25 * The ActivityPub Protocol is a message exchange protocol defined by the W3C.
26 * https://www.w3.org/TR/activitypub/
27 * https://www.w3.org/TR/activitystreams-core/
28 * https://www.w3.org/TR/activitystreams-vocabulary/
30 * https://blog.joinmastodon.org/2018/06/how-to-implement-a-basic-activitypub-server/
31 * https://blog.joinmastodon.org/2018/07/how-to-make-friends-and-verify-requests/
33 * Digest: https://tools.ietf.org/html/rfc5843
34 * https://tools.ietf.org/html/draft-cavage-http-signatures-10#ref-15
35 * https://github.com/digitalbazaar/php-json-ld
37 * Part of the code for HTTP signing is taken from the Osada project.
38 * https://framagit.org/macgirvin/osada
43 * - Activities: Dislike, Update, Delete
44 * - Object Types: Person, Tombstome
47 * - Activities: Like, Dislike, Update, Delete
48 * - Object Tyoes: Article, Announce, Person, Tombstone
51 * - Message distribution
52 * - Endpoints: Outbox, Object, Follower, Following
57 const PUBLIC = 'https://www.w3.org/ns/activitystreams#Public';
59 public static function isRequest()
61 return stristr(defaults($_SERVER, 'HTTP_ACCEPT', ''), 'application/activity+json') ||
62 stristr(defaults($_SERVER, 'HTTP_ACCEPT', ''), 'application/ld+json');
65 public static function transmit($data, $target, $uid)
67 $owner = User::getOwnerDataById($uid);
73 $content = json_encode($data);
75 // Header data that is about to be signed.
76 $host = parse_url($target, PHP_URL_HOST);
77 $path = parse_url($target, PHP_URL_PATH);
78 $digest = 'SHA-256=' . base64_encode(hash('sha256', $content, true));
79 $content_length = strlen($content);
81 $headers = ['Content-Length: ' . $content_length, 'Digest: ' . $digest, 'Host: ' . $host];
83 $signed_data = "(request-target): post " . $path . "\ncontent-length: " . $content_length . "\ndigest: " . $digest . "\nhost: " . $host;
85 $signature = base64_encode(Crypto::rsaSign($signed_data, $owner['uprvkey'], 'sha256'));
87 $headers[] = 'Signature: keyId="' . $owner['url'] . '#main-key' . '",algorithm="rsa-sha256",headers="(request-target) content-length digest host",signature="' . $signature . '"';
89 $headers[] = 'Content-Type: application/activity+json';
91 Network::post($target, $content, $headers);
92 $return_code = BaseObject::getApp()->get_curl_code();
94 logger('Transmit to ' . $target . ' returned ' . $return_code);
98 * Return the ActivityPub profile of the given user
100 * @param integer $uid User ID
103 public static function profile($uid)
105 $accounttype = ['Person', 'Organization', 'Service', 'Group', 'Application', 'page-flags'];
106 $condition = ['uid' => $uid, 'blocked' => false, 'account_expired' => false,
107 'account_removed' => false, 'verified' => true];
108 $fields = ['guid', 'nickname', 'pubkey', 'account-type'];
109 $user = DBA::selectFirst('user', $fields, $condition);
110 if (!DBA::isResult($user)) {
114 $fields = ['locality', 'region', 'country-name'];
115 $profile = DBA::selectFirst('profile', $fields, ['uid' => $uid, 'is-default' => true]);
116 if (!DBA::isResult($profile)) {
120 $fields = ['name', 'url', 'location', 'about', 'avatar'];
121 $contact = DBA::selectFirst('contact', $fields, ['uid' => $uid, 'self' => true]);
122 if (!DBA::isResult($contact)) {
126 $data = ['@context' => ['https://www.w3.org/ns/activitystreams', 'https://w3id.org/security/v1',
127 ['vcard' => 'http://www.w3.org/2006/vcard/ns#', 'uuid' => 'http://schema.org/identifier',
128 'sensitive' => 'as:sensitive', 'manuallyApprovesFollowers' => 'as:manuallyApprovesFollowers']]];
130 $data['id'] = $contact['url'];
131 $data['uuid'] = $user['guid'];
132 $data['type'] = $accounttype[$user['account-type']];
133 $data['following'] = System::baseUrl() . '/following/' . $user['nickname'];
134 $data['followers'] = System::baseUrl() . '/followers/' . $user['nickname'];
135 $data['inbox'] = System::baseUrl() . '/inbox/' . $user['nickname'];
136 $data['outbox'] = System::baseUrl() . '/outbox/' . $user['nickname'];
137 $data['preferredUsername'] = $user['nickname'];
138 $data['name'] = $contact['name'];
139 $data['vcard:hasAddress'] = ['@type' => 'vcard:Home', 'vcard:country-name' => $profile['country-name'],
140 'vcard:region' => $profile['region'], 'vcard:locality' => $profile['locality']];
141 $data['summary'] = $contact['about'];
142 $data['url'] = $contact['url'];
143 $data['manuallyApprovesFollowers'] = in_array($profile['page-flags'], [Contact::PAGE_NORMAL, Contact::PAGE_PRVGROUP]);
144 $data['publicKey'] = ['id' => $contact['url'] . '#main-key',
145 'owner' => $contact['url'],
146 'publicKeyPem' => $user['pubkey']];
147 $data['endpoints'] = ['sharedInbox' => System::baseUrl() . '/inbox'];
148 $data['icon'] = ['type' => 'Image',
149 'url' => $contact['avatar']];
151 // tags: https://kitty.town/@inmysocks/100656097926961126.json
155 public static function createPermissionBlockForItem($item)
157 $data = ['to' => [], 'cc' => []];
159 $terms = Term::tagArrayFromItemId($item['id']);
161 if (!$item['private']) {
162 $data['to'][] = self::PUBLIC;
163 $data['cc'][] = System::baseUrl() . '/followers/' . $item['author-nick'];
165 foreach ($terms as $term) {
166 if ($term['type'] != TERM_MENTION) {
169 $profile = self::fetchprofile($term['url']);
170 if (!empty($profile)) {
171 $data['cc'][] = $profile['url'];
175 //$data['cc'][] = System::baseUrl() . '/followers/' . $item['author-nick'];
176 $receiver_list = Item::enumeratePermissions($item);
180 foreach ($terms as $term) {
181 if ($term['type'] != TERM_MENTION) {
184 $cid = Contact::getIdForURL($term['url'], $item['uid']);
185 if (!empty($cid) && in_array($cid, $receiver_list)) {
186 $contact = DBA::selectFirst('contact', ['url'], ['id' => $cid, 'network' => Protocol::ACTIVITYPUB]);
187 $data['to'][] = $contact['url'];
191 foreach ($receiver_list as $receiver) {
192 $contact = DBA::selectFirst('contact', ['url'], ['id' => $receiver, 'network' => Protocol::ACTIVITYPUB]);
193 $data['cc'][] = $contact['url'];
196 if (empty($data['to'])) {
197 $data['to'] = $data['cc'];
205 public static function fetchTargetInboxes($item)
209 $terms = Term::tagArrayFromItemId($item['id']);
210 if (!$item['private']) {
211 $contacts = DBA::select('contact', ['notify', 'batch'], ['uid' => $item['uid'],
212 'rel' => [Contact::FOLLOWER, Contact::FRIEND], 'network' => Protocol::ACTIVITYPUB]);
213 while ($contact = DBA::fetch($contacts)) {
214 $contact = defaults($contact, 'batch', $contact['notify']);
215 $inboxes[$contact] = $contact;
217 DBA::close($contacts);
219 foreach ($terms as $term) {
220 if ($term['type'] != TERM_MENTION) {
223 $profile = self::fetchprofile($term['url']);
224 if (!empty($profile)) {
225 $target = defaults($profile, 'sharedinbox', $profile['inbox']);
226 $inboxes[$target] = $target;
230 $receiver_list = Item::enumeratePermissions($item);
234 foreach ($terms as $term) {
235 if ($term['type'] != TERM_MENTION) {
238 $cid = Contact::getIdForURL($term['url'], $item['uid']);
239 if (!empty($cid) && in_array($cid, $receiver_list)) {
240 $contact = DBA::selectFirst('contact', ['url'], ['id' => $cid, 'network' => Protocol::ACTIVITYPUB]);
241 $profile = self::fetchprofile($contact['url']);
242 if (!empty($profile['network'])) {
243 $target = defaults($profile, 'sharedinbox', $profile['inbox']);
244 $inboxes[$target] = $target;
249 foreach ($receiver_list as $receiver) {
250 $contact = DBA::selectFirst('contact', ['url'], ['id' => $receiver, 'network' => Protocol::ACTIVITYPUB]);
251 $profile = self::fetchprofile($contact['url']);
252 if (!empty($profile['network'])) {
253 $target = defaults($profile, 'sharedinbox', $profile['inbox']);
254 $inboxes[$target] = $target;
259 $profile = self::fetchprofile($item['author-link']);
260 if (!empty($profile['sharedinbox'])) {
261 unset($inboxes[$profile['sharedinbox']]);
264 if (!empty($profile['inbox'])) {
265 unset($inboxes[$profile['inbox']]);
271 public static function createActivityFromItem($item_id)
273 $item = Item::selectFirst([], ['id' => $item_id]);
275 if (!DBA::isResult($item)) {
279 $condition = ['item-uri' => $item['uri'], 'protocol' => Conversation::PARCEL_ACTIVITYPUB];
280 $conversation = DBA::selectFirst('conversation', ['source'], $condition);
281 if (DBA::isResult($conversation)) {
282 $data = json_decode($conversation['source']);
288 $data = ['@context' => ['https://www.w3.org/ns/activitystreams', 'https://w3id.org/security/v1',
289 ['ostatus' => 'http://ostatus.org#', 'sensitive' => 'as:sensitive',
290 'Hashtag' => 'as:Hashtag', 'atomUri' => 'ostatus:atomUri',
291 'conversation' => 'ostatus:conversation',
292 'inReplyToAtomUri' => 'ostatus:inReplyToAtomUri']]];
294 $data['type'] = 'Create';
295 $data['id'] = $item['uri'] . '#activity';
296 $data['actor'] = $item['author-link'];
298 $data['published'] = DateTimeFormat::utc($item["created"]."+00:00", DateTimeFormat::ATOM);
300 if ($item["created"] != $item["edited"]) {
301 $data['updated'] = DateTimeFormat::utc($item["edited"]."+00:00", DateTimeFormat::ATOM);
304 $data = array_merge($data, ActivityPub::createPermissionBlockForItem($item));
306 $data['object'] = self::createNote($item);
310 public static function createObjectFromItemID($item_id)
312 $item = Item::selectFirst([], ['id' => $item_id]);
314 if (!DBA::isResult($item)) {
318 $data = ['@context' => ['https://www.w3.org/ns/activitystreams', 'https://w3id.org/security/v1',
319 ['ostatus' => 'http://ostatus.org#', 'sensitive' => 'as:sensitive',
320 'Hashtag' => 'as:Hashtag', 'atomUri' => 'ostatus:atomUri',
321 'conversation' => 'ostatus:conversation',
322 'inReplyToAtomUri' => 'ostatus:inReplyToAtomUri']]];
324 $data = array_merge($data, self::createNote($item));
330 private static function createTagList($item)
334 $terms = Term::tagArrayFromItemId($item['id']);
335 foreach ($terms as $term) {
336 if ($term['type'] == TERM_MENTION) {
337 $contact = Contact::getDetailsByURL($term['url']);
338 if (!empty($contact['addr'])) {
339 $mention = '@' . $contact['addr'];
341 $mention = '@' . $term['url'];
344 $tags[] = ['type' => 'Mention', 'href' => $term['url'], 'name' => $mention];
351 public static function createNote($item)
354 $data['type'] = 'Note';
355 $data['id'] = $item['uri'];
357 if ($item['uri'] != $item['thr-parent']) {
358 $data['inReplyTo'] = $item['thr-parent'];
361 $conversation = DBA::selectFirst('conversation', ['conversation-uri'], ['item-uri' => $item['parent-uri']]);
362 if (DBA::isResult($conversation) && !empty($conversation['conversation-uri'])) {
363 $conversation_uri = $conversation['conversation-uri'];
365 $conversation_uri = $item['parent-uri'];
368 $data['context'] = $data['conversation'] = $conversation_uri;
369 $data['actor'] = $item['author-link'];
370 $data = array_merge($data, ActivityPub::createPermissionBlockForItem($item));
371 $data['published'] = DateTimeFormat::utc($item["created"]."+00:00", DateTimeFormat::ATOM);
373 if ($item["created"] != $item["edited"]) {
374 $data['updated'] = DateTimeFormat::utc($item["edited"]."+00:00", DateTimeFormat::ATOM);
377 $data['attributedTo'] = $item['author-link'];
378 $data['name'] = BBCode::convert($item['title'], false, 7);
379 $data['content'] = BBCode::convert($item['body'], false, 7);
380 $data['source'] = ['content' => $item['body'], 'mediaType' => "text/bbcode"];
381 $data['summary'] = ''; // Ignore by now
382 $data['sensitive'] = false; // - Query NSFW
383 //$data['emoji'] = []; // Ignore by now
384 $data['tag'] = self::createTagList($item);
385 $data['attachment'] = []; // @ToDo
389 public static function transmitActivity($activity, $target, $uid)
391 $profile = self::fetchprofile($target);
393 $owner = User::getOwnerDataById($uid);
395 $data = ['@context' => 'https://www.w3.org/ns/activitystreams',
396 'id' => System::baseUrl() . '/activity/' . System::createGUID(),
398 'actor' => $owner['url'],
399 'object' => $profile['url'],
400 'to' => $profile['url']];
402 logger('Sending activity ' . $activity . ' to ' . $target . ' for user ' . $uid, LOGGER_DEBUG);
403 return self::transmit($data, $profile['inbox'], $uid);
406 public static function transmitContactAccept($target, $id, $uid)
408 $profile = self::fetchprofile($target);
410 $owner = User::getOwnerDataById($uid);
411 $data = ['@context' => 'https://www.w3.org/ns/activitystreams',
412 'id' => System::baseUrl() . '/activity/' . System::createGUID(),
414 'actor' => $owner['url'],
415 'object' => ['id' => $id, 'type' => 'Follow',
416 'actor' => $profile['url'],
417 'object' => $owner['url']],
418 'to' => $profile['url']];
420 logger('Sending accept to ' . $target . ' for user ' . $uid . ' with id ' . $id, LOGGER_DEBUG);
421 return self::transmit($data, $profile['inbox'], $uid);
424 public static function transmitContactReject($target, $id, $uid)
426 $profile = self::fetchprofile($target);
428 $owner = User::getOwnerDataById($uid);
429 $data = ['@context' => 'https://www.w3.org/ns/activitystreams',
430 'id' => System::baseUrl() . '/activity/' . System::createGUID(),
432 'actor' => $owner['url'],
433 'object' => ['id' => $id, 'type' => 'Follow',
434 'actor' => $profile['url'],
435 'object' => $owner['url']],
436 'to' => $profile['url']];
438 logger('Sending reject to ' . $target . ' for user ' . $uid . ' with id ' . $id, LOGGER_DEBUG);
439 return self::transmit($data, $profile['inbox'], $uid);
442 public static function transmitContactUndo($target, $uid)
444 $profile = self::fetchprofile($target);
446 $id = System::baseUrl() . '/activity/' . System::createGUID();
448 $owner = User::getOwnerDataById($uid);
449 $data = ['@context' => 'https://www.w3.org/ns/activitystreams',
452 'actor' => $owner['url'],
453 'object' => ['id' => $id, 'type' => 'Follow',
454 'actor' => $owner['url'],
455 'object' => $profile['url']],
456 'to' => $profile['url']];
458 logger('Sending undo to ' . $target . ' for user ' . $uid . ' with id ' . $id, LOGGER_DEBUG);
459 return self::transmit($data, $profile['inbox'], $uid);
463 * Fetches ActivityPub content from the given url
465 * @param string $url content url
468 public static function fetchContent($url)
470 $ret = Network::curl($url, false, $redirects, ['accept_content' => 'application/activity+json, application/ld+json']);
471 if (!$ret['success'] || empty($ret['body'])) {
475 return json_decode($ret['body'], true);
479 * Resolves the profile url from the address by using webfinger
481 * @param string $addr profile address (user@domain.tld)
484 private static function addrToUrl($addr)
486 $addr_parts = explode('@', $addr);
487 if (count($addr_parts) != 2) {
491 $webfinger = 'https://' . $addr_parts[1] . '/.well-known/webfinger?resource=acct:' . urlencode($addr);
493 $ret = Network::curl($webfinger, false, $redirects, ['accept_content' => 'application/jrd+json,application/json']);
494 if (!$ret['success'] || empty($ret['body'])) {
498 $data = json_decode($ret['body'], true);
500 if (empty($data['links'])) {
504 foreach ($data['links'] as $link) {
505 if (empty($link['href']) || empty($link['rel']) || empty($link['type'])) {
509 if (($link['rel'] == 'self') && ($link['type'] == 'application/activity+json')) {
510 return $link['href'];
517 public static function verifySignature($content, $http_headers)
519 $object = json_decode($content, true);
521 if (empty($object)) {
525 $actor = self::processElement($object, 'actor', 'id');
528 $headers['(request-target)'] = strtolower($http_headers['REQUEST_METHOD']) . ' ' . $http_headers['REQUEST_URI'];
530 // First take every header
531 foreach ($http_headers as $k => $v) {
532 $field = str_replace('_', '-', strtolower($k));
533 $headers[$field] = $v;
536 // Now add every http header
537 foreach ($http_headers as $k => $v) {
538 if (strpos($k, 'HTTP_') === 0) {
539 $field = str_replace('_', '-', strtolower(substr($k, 5)));
540 $headers[$field] = $v;
544 $sig_block = ActivityPub::parseSigHeader($http_headers['HTTP_SIGNATURE']);
546 if (empty($sig_block) || empty($sig_block['headers']) || empty($sig_block['keyId'])) {
551 foreach ($sig_block['headers'] as $h) {
552 if (array_key_exists($h, $headers)) {
553 $signed_data .= $h . ': ' . $headers[$h] . "\n";
556 $signed_data = rtrim($signed_data, "\n");
558 if (empty($signed_data)) {
564 if ($sig_block['algorithm'] === 'rsa-sha256') {
565 $algorithm = 'sha256';
568 if ($sig_block['algorithm'] === 'rsa-sha512') {
569 $algorithm = 'sha512';
572 if (empty($algorithm)) {
576 $key = self::fetchKey($sig_block['keyId'], $actor);
582 if (!Crypto::rsaVerify($signed_data, $sig_block['signature'], $key, $algorithm)) {
586 // Check the digest when it is part of the signed data
587 if (in_array('digest', $sig_block['headers'])) {
588 $digest = explode('=', $headers['digest'], 2);
589 if ($digest[0] === 'SHA-256') {
592 if ($digest[0] === 'SHA-512') {
596 /// @todo add all hashes from the rfc
598 if (!empty($hashalg) && base64_encode(hash($hashalg, $content, true)) != $digest[1]) {
603 // Check the content-length when it is part of the signed data
604 if (in_array('content-length', $sig_block['headers'])) {
605 if (strlen($content) != $headers['content-length']) {
614 private static function fetchKey($id, $actor)
616 $url = (strpos($id, '#') ? substr($id, 0, strpos($id, '#')) : $id);
618 $profile = self::fetchprofile($url);
619 if (!empty($profile)) {
620 return $profile['pubkey'];
621 } elseif ($url != $actor) {
622 $profile = self::fetchprofile($actor);
623 if (!empty($profile)) {
624 return $profile['pubkey'];
634 * @param string $header
635 * @return array associate array with
636 * - \e string \b keyID
637 * - \e string \b algorithm
638 * - \e array \b headers
639 * - \e string \b signature
641 private static function parseSigHeader($header)
646 if (preg_match('/keyId="(.*?)"/ism',$header,$matches)) {
647 $ret['keyId'] = $matches[1];
650 if (preg_match('/algorithm="(.*?)"/ism',$header,$matches)) {
651 $ret['algorithm'] = $matches[1];
654 if (preg_match('/headers="(.*?)"/ism',$header,$matches)) {
655 $ret['headers'] = explode(' ', $matches[1]);
658 if (preg_match('/signature="(.*?)"/ism',$header,$matches)) {
659 $ret['signature'] = base64_decode(preg_replace('/\s+/','',$matches[1]));
665 public static function fetchprofile($url, $update = false)
672 $apcontact = DBA::selectFirst('apcontact', [], ['url' => $url]);
673 if (DBA::isResult($apcontact)) {
677 $apcontact = DBA::selectFirst('apcontact', [], ['alias' => $url]);
678 if (DBA::isResult($apcontact)) {
682 $apcontact = DBA::selectFirst('apcontact', [], ['addr' => $url]);
683 if (DBA::isResult($apcontact)) {
688 if (empty(parse_url($url, PHP_URL_SCHEME))) {
689 $url = self::addrToUrl($url);
695 $data = self::fetchContent($url);
697 if (empty($data) || empty($data['id']) || empty($data['inbox'])) {
702 $apcontact['url'] = $data['id'];
703 $apcontact['uuid'] = defaults($data, 'uuid', null);
704 $apcontact['type'] = defaults($data, 'type', null);
705 $apcontact['following'] = defaults($data, 'following', null);
706 $apcontact['followers'] = defaults($data, 'followers', null);
707 $apcontact['inbox'] = defaults($data, 'inbox', null);
708 $apcontact['outbox'] = defaults($data, 'outbox', null);
709 $apcontact['sharedinbox'] = self::processElement($data, 'endpoints', 'sharedInbox');
710 $apcontact['nick'] = defaults($data, 'preferredUsername', null);
711 $apcontact['name'] = defaults($data, 'name', $apcontact['nick']);
712 $apcontact['about'] = defaults($data, 'summary', '');
713 $apcontact['photo'] = self::processElement($data, 'icon', 'url');
714 $apcontact['alias'] = self::processElement($data, 'url', 'href');
716 $parts = parse_url($apcontact['url']);
717 unset($parts['scheme']);
718 unset($parts['path']);
719 $apcontact['addr'] = $apcontact['nick'] . '@' . str_replace('//', '', Network::unparseURL($parts));
721 $apcontact['pubkey'] = trim(self::processElement($data, 'publicKey', 'publicKeyPem'));
724 // manuallyApprovesFollowers
727 // @context, tag, attachment, image, nomadicLocations, signature, following, followers, featured, movedTo, liked
729 // Unhandled from Misskey
730 // sharedInbox, isCat
732 // Unhandled from Kroeg
733 // kroeg:blocks, updated
735 // Check if the address is resolvable
736 if (self::addrToUrl($apcontact['addr']) == $apcontact['url']) {
737 $parts = parse_url($apcontact['url']);
738 unset($parts['path']);
739 $apcontact['baseurl'] = Network::unparseURL($parts);
741 $apcontact['addr'] = null;
744 if ($apcontact['url'] == $apcontact['alias']) {
745 $apcontact['alias'] = null;
748 $apcontact['updated'] = DateTimeFormat::utcNow();
750 DBA::update('apcontact', $apcontact, ['url' => $url], true);
756 * Fetches a profile from the given url into an array that is compatible to Probe::uri
758 * @param string $url profile url
761 public static function probeProfile($url)
763 $apcontact = self::fetchprofile($url, true);
764 if (empty($apcontact)) {
768 $profile = ['network' => Protocol::ACTIVITYPUB];
769 $profile['nick'] = $apcontact['nick'];
770 $profile['name'] = $apcontact['name'];
771 $profile['guid'] = $apcontact['uuid'];
772 $profile['url'] = $apcontact['url'];
773 $profile['addr'] = $apcontact['addr'];
774 $profile['alias'] = $apcontact['alias'];
775 $profile['photo'] = $apcontact['photo'];
776 // $profile['community']
777 // $profile['keywords']
778 // $profile['location']
779 $profile['about'] = $apcontact['about'];
780 $profile['batch'] = $apcontact['sharedinbox'];
781 $profile['notify'] = $apcontact['inbox'];
782 $profile['poll'] = $apcontact['outbox'];
783 $profile['pubkey'] = $apcontact['pubkey'];
784 $profile['baseurl'] = $apcontact['baseurl'];
786 // Remove all "null" fields
787 foreach ($profile as $field => $content) {
788 if (is_null($content)) {
789 unset($profile[$field]);
796 public static function processInbox($body, $header, $uid)
798 logger('Incoming message for user ' . $uid, LOGGER_DEBUG);
800 if (!self::verifySignature($body, $header)) {
801 logger('Invalid signature, message will be discarded.', LOGGER_DEBUG);
805 $activity = json_decode($body, true);
807 if (!is_array($activity)) {
808 logger('Invalid body.', LOGGER_DEBUG);
812 self::processActivity($activity, $body, $uid);
815 public static function fetchOutbox($url)
817 $data = self::fetchContent($url);
822 if (!empty($data['orderedItems'])) {
823 $items = $data['orderedItems'];
824 } elseif (!empty($data['first']['orderedItems'])) {
825 $items = $data['first']['orderedItems'];
826 } elseif (!empty($data['first'])) {
827 self::fetchOutbox($data['first']);
833 foreach ($items as $activity) {
834 self::processActivity($activity);
838 private static function prepareObjectData($activity, $uid)
840 $actor = self::processElement($activity, 'actor', 'id');
842 logger('Empty actor', LOGGER_DEBUG);
846 // Fetch all receivers from to, cc, bto and bcc
847 $receivers = self::getReceivers($activity, $actor);
849 // When it is a delivery to a personal inbox we add that user to the receivers
851 $owner = User::getOwnerDataById($uid);
852 $additional = ['uid:' . $uid => $uid];
853 $receivers = array_merge($receivers, $additional);
856 logger('Receivers: ' . json_encode($receivers), LOGGER_DEBUG);
858 $public = in_array(0, $receivers);
860 if (is_string($activity['object'])) {
861 $object_url = $activity['object'];
862 } elseif (!empty($activity['object']['id'])) {
863 $object_url = $activity['object']['id'];
865 logger('No object found', LOGGER_DEBUG);
869 // Fetch the content only on activities where this matters
870 if (in_array($activity['type'], ['Create', 'Update', 'Announce'])) {
871 $object_data = self::fetchObject($object_url, $activity['object']);
872 if (empty($object_data)) {
873 logger("Object data couldn't be processed", LOGGER_DEBUG);
876 } elseif ($activity['type'] == 'Accept') {
878 $object_data['object_type'] = self::processElement($activity, 'object', 'type');
879 $object_data['object'] = self::processElement($activity, 'object', 'actor');
880 } elseif ($activity['type'] == 'Undo') {
882 $object_data['object_type'] = self::processElement($activity, 'object', 'type');
883 $object_data['object'] = self::processElement($activity, 'object', 'object');
884 } elseif (in_array($activity['type'], ['Like', 'Dislike'])) {
885 // Create a mostly empty array out of the activity data (instead of the object).
886 // This way we later don't have to check for the existence of ech individual array element.
887 $object_data = self::processCommonData($activity);
888 $object_data['name'] = $activity['type'];
889 $object_data['author'] = $activity['actor'];
890 $object_data['object'] = $object_url;
891 } elseif ($activity['type'] == 'Follow') {
892 $object_data['id'] = $activity['id'];
893 $object_data['object'] = $object_url;
898 $object_data = self::addActivityFields($object_data, $activity);
900 $object_data['type'] = $activity['type'];
901 $object_data['owner'] = $actor;
902 $object_data['receiver'] = array_merge(defaults($object_data, 'receiver', []), $receivers);
907 private static function processActivity($activity, $body = '', $uid = null)
909 if (empty($activity['type'])) {
910 logger('Empty type', LOGGER_DEBUG);
914 if (empty($activity['object'])) {
915 logger('Empty object', LOGGER_DEBUG);
919 if (empty($activity['actor'])) {
920 logger('Empty actor', LOGGER_DEBUG);
926 // title, atomUri, context_id, statusnetConversationId
929 // context, location, signature;
931 logger('Processing activity: ' . $activity['type'], LOGGER_DEBUG);
933 $object_data = self::prepareObjectData($activity, $uid);
934 if (empty($object_data)) {
935 logger('No object data found', LOGGER_DEBUG);
939 switch ($activity['type']) {
942 self::createItem($object_data, $body);
946 self::likeItem($object_data, $body);
959 self::followUser($object_data);
963 if ($object_data['object_type'] == 'Follow') {
964 self::acceptFollowUser($object_data);
969 if ($object_data['object_type'] == 'Follow') {
970 self::undoFollowUser($object_data);
975 logger('Unknown activity: ' . $activity['type'], LOGGER_DEBUG);
980 private static function getReceivers($activity, $actor)
984 if (!empty($actor)) {
985 $profile = self::fetchprofile($actor);
986 $followers = defaults($profile, 'followers', '');
988 logger('Actor: ' . $actor . ' - Followers: ' . $followers, LOGGER_DEBUG);
990 logger('Empty actor', LOGGER_DEBUG);
994 $elements = ['to', 'cc', 'bto', 'bcc'];
995 foreach ($elements as $element) {
996 if (empty($activity[$element])) {
1000 // The receiver can be an arror or a string
1001 if (is_string($activity[$element])) {
1002 $activity[$element] = [$activity[$element]];
1005 foreach ($activity[$element] as $receiver) {
1006 if ($receiver == self::PUBLIC) {
1007 $receivers['uid:0'] = 0;
1010 if (($receiver == self::PUBLIC) && !empty($actor)) {
1011 // This will most likely catch all OStatus connections to Mastodon
1012 $condition = ['alias' => [$actor, normalise_link($actor)], 'rel' => [Contact::SHARING, Contact::FRIEND]];
1013 $contacts = DBA::select('contact', ['uid'], $condition);
1014 while ($contact = DBA::fetch($contacts)) {
1015 if ($contact['uid'] != 0) {
1016 $receivers['uid:' . $contact['uid']] = $contact['uid'];
1019 DBA::close($contacts);
1022 if (in_array($receiver, [$followers, self::PUBLIC]) && !empty($actor)) {
1023 $condition = ['nurl' => normalise_link($actor), 'rel' => [Contact::SHARING, Contact::FRIEND],
1024 'network' => Protocol::ACTIVITYPUB];
1025 $contacts = DBA::select('contact', ['uid'], $condition);
1026 while ($contact = DBA::fetch($contacts)) {
1027 if ($contact['uid'] != 0) {
1028 $receivers['uid:' . $contact['uid']] = $contact['uid'];
1031 DBA::close($contacts);
1035 $condition = ['self' => true, 'nurl' => normalise_link($receiver)];
1036 $contact = DBA::selectFirst('contact', ['uid'], $condition);
1037 if (!DBA::isResult($contact)) {
1040 $receivers['uid:' . $contact['uid']] = $contact['uid'];
1046 private static function addActivityFields($object_data, $activity)
1048 if (!empty($activity['published']) && empty($object_data['published'])) {
1049 $object_data['published'] = $activity['published'];
1052 if (!empty($activity['updated']) && empty($object_data['updated'])) {
1053 $object_data['updated'] = $activity['updated'];
1056 if (!empty($activity['inReplyTo']) && empty($object_data['parent-uri'])) {
1057 $object_data['parent-uri'] = self::processElement($activity, 'inReplyTo', 'id');
1060 if (!empty($activity['instrument'])) {
1061 $object_data['service'] = self::processElement($activity, 'instrument', 'name', 'type', 'Service');
1063 return $object_data;
1066 private static function fetchObject($object_url, $object = [], $public = true)
1069 $data = self::fetchContent($object_url);
1071 logger('Empty content for ' . $object_url . ', check if content is available locally.', LOGGER_DEBUG);
1072 $data = $object_url;
1076 logger('Using original object for url ' . $object_url, LOGGER_DEBUG);
1080 if (is_string($data)) {
1081 $item = Item::selectFirst([], ['uri' => $data]);
1082 if (!DBA::isResult($item)) {
1083 logger('Object with url ' . $data . ' was not found locally.', LOGGER_DEBUG);
1086 logger('Using already stored item for url ' . $object_url, LOGGER_DEBUG);
1087 $data = self::createNote($item);
1090 if (empty($data['type'])) {
1091 logger('Empty type', LOGGER_DEBUG);
1094 $type = $data['type'];
1095 logger('Type ' . $type, LOGGER_DEBUG);
1098 if (in_array($type, ['Note', 'Article', 'Video'])) {
1099 $common = self::processCommonData($data);
1104 return array_merge($common, self::processNote($data));
1106 return array_merge($common, self::processArticle($data));
1108 return array_merge($common, self::processVideo($data));
1111 if (empty($data['object'])) {
1114 return self::fetchObject($data['object']);
1121 logger('Unknown object type: ' . $data['type'], LOGGER_DEBUG);
1126 private static function processCommonData(&$object)
1128 if (empty($object['id'])) {
1133 $object_data['type'] = $object['type'];
1134 $object_data['uri'] = $object['id'];
1136 if (!empty($object['inReplyTo'])) {
1137 $object_data['reply-to-uri'] = self::processElement($object, 'inReplyTo', 'id');
1139 $object_data['reply-to-uri'] = $object_data['uri'];
1142 $object_data['published'] = defaults($object, 'published', null);
1143 $object_data['updated'] = defaults($object, 'updated', $object_data['published']);
1145 if (empty($object_data['published']) && !empty($object_data['updated'])) {
1146 $object_data['published'] = $object_data['updated'];
1149 $object_data['uuid'] = defaults($object, 'uuid', null);
1150 $object_data['owner'] = $object_data['author'] = self::processElement($object, 'attributedTo', 'id');
1151 $object_data['context'] = defaults($object, 'context', null);
1152 $object_data['conversation'] = defaults($object, 'conversation', null);
1153 $object_data['sensitive'] = defaults($object, 'sensitive', null);
1154 $object_data['name'] = defaults($object, 'title', null);
1155 $object_data['name'] = defaults($object, 'name', $object_data['name']);
1156 $object_data['summary'] = defaults($object, 'summary', null);
1157 $object_data['content'] = defaults($object, 'content', null);
1158 $object_data['source'] = defaults($object, 'source', null);
1159 $object_data['location'] = self::processElement($object, 'location', 'name', 'type', 'Place');
1160 $object_data['attachments'] = defaults($object, 'attachment', null);
1161 $object_data['tags'] = defaults($object, 'tag', null);
1162 $object_data['service'] = self::processElement($object, 'instrument', 'name', 'type', 'Service');
1163 $object_data['alternate-url'] = self::processElement($object, 'url', 'href');
1164 $object_data['receiver'] = self::getReceivers($object, $object_data['owner']);
1167 // @context, type, actor, signature, mediaType, duration, replies, icon
1169 // Also missing: (Defined in the standard, but currently unused)
1170 // audience, preview, endTime, startTime, generator, image
1172 return $object_data;
1175 private static function processNote($object)
1180 // emoji, atomUri, inReplyToAtomUri
1183 // contentMap, announcement_count, announcements, context_id, likes, like_count
1184 // inReplyToStatusId, shares, quoteUrl, statusnetConversationId
1186 return $object_data;
1189 private static function processArticle($object)
1193 return $object_data;
1196 private static function processVideo($object)
1201 // category, licence, language, commentsEnabled
1204 // views, waitTranscoding, state, support, subtitleLanguage
1205 // likes, dislikes, shares, comments
1207 return $object_data;
1210 private static function processElement($array, $element, $key, $type = null, $type_value = null)
1212 if (empty($array)) {
1216 if (empty($array[$element])) {
1220 if (is_string($array[$element])) {
1221 return $array[$element];
1224 if (is_null($type_value)) {
1225 if (!empty($array[$element][$key])) {
1226 return $array[$element][$key];
1229 if (!empty($array[$element][0][$key])) {
1230 return $array[$element][0][$key];
1236 if (!empty($array[$element][$key]) && !empty($array[$element][$type]) && ($array[$element][$type] == $type_value)) {
1237 return $array[$element][$key];
1240 /// @todo Add array search
1245 private static function convertMentions($body)
1247 $URLSearchString = "^\[\]";
1248 $body = preg_replace("/\[url\=([$URLSearchString]*)\]([#@!])(.*?)\[\/url\]/ism", '$2[url=$1]$3[/url]', $body);
1253 private static function constructTagList($tags, $sensitive)
1260 foreach ($tags as $tag) {
1261 if (in_array($tag['type'], ['Mention', 'Hashtag'])) {
1262 if (!empty($tag_text)) {
1266 if (empty($tag['href'])) {
1271 $tag_text .= substr($tag['name'], 0, 1) . '[url=' . $tag['href'] . ']' . substr($tag['name'], 1) . '[/url]';
1275 /// @todo add nsfw for $sensitive
1280 private static function constructAttachList($attachments, $item)
1282 if (empty($attachments)) {
1286 foreach ($attachments as $attach) {
1287 $filetype = strtolower(substr($attach['mediaType'], 0, strpos($attach['mediaType'], '/')));
1288 if ($filetype == 'image') {
1289 $item['body'] .= "\n[img]".$attach['url'].'[/img]';
1291 if (!empty($item["attach"])) {
1292 $item["attach"] .= ',';
1294 $item["attach"] = '';
1296 if (!isset($attach['length'])) {
1297 $attach['length'] = "0";
1299 $item["attach"] .= '[attach]href="'.$attach['url'].'" length="'.$attach['length'].'" type="'.$attach['mediaType'].'" title="'.defaults($attach, 'name', '').'"[/attach]';
1306 private static function createItem($activity, $body)
1309 $item['verb'] = ACTIVITY_POST;
1310 $item['parent-uri'] = $activity['reply-to-uri'];
1312 if ($activity['reply-to-uri'] == $activity['uri']) {
1313 $item['gravity'] = GRAVITY_PARENT;
1314 $item['object-type'] = ACTIVITY_OBJ_NOTE;
1316 $item['gravity'] = GRAVITY_COMMENT;
1317 $item['object-type'] = ACTIVITY_OBJ_COMMENT;
1320 if (($activity['uri'] != $activity['reply-to-uri']) && !Item::exists(['uri' => $activity['reply-to-uri']])) {
1321 logger('Parent ' . $activity['reply-to-uri'] . ' not found. Try to refetch it.');
1322 self::fetchMissingActivity($activity['reply-to-uri'], $activity);
1325 self::postItem($activity, $item, $body);
1328 private static function likeItem($activity, $body)
1331 $item['verb'] = ACTIVITY_LIKE;
1332 $item['parent-uri'] = $activity['object'];
1333 $item['gravity'] = GRAVITY_ACTIVITY;
1334 $item['object-type'] = ACTIVITY_OBJ_NOTE;
1336 self::postItem($activity, $item, $body);
1339 private static function postItem($activity, $item, $body)
1341 /// @todo What to do with $activity['context']?
1343 $item['network'] = Protocol::ACTIVITYPUB;
1344 $item['private'] = !in_array(0, $activity['receiver']);
1345 $item['author-id'] = Contact::getIdForURL($activity['author'], 0, true);
1346 $item['owner-id'] = Contact::getIdForURL($activity['owner'], 0, true);
1347 $item['uri'] = $activity['uri'];
1348 $item['created'] = $activity['published'];
1349 $item['edited'] = $activity['updated'];
1350 $item['guid'] = $activity['uuid'];
1351 $item['title'] = HTML::toBBCode($activity['name']);
1352 $item['content-warning'] = HTML::toBBCode($activity['summary']);
1353 $item['body'] = self::convertMentions(HTML::toBBCode($activity['content']));
1354 $item['location'] = $activity['location'];
1355 $item['tag'] = self::constructTagList($activity['tags'], $activity['sensitive']);
1356 $item['app'] = $activity['service'];
1357 $item['plink'] = defaults($activity, 'alternate-url', $item['uri']);
1359 $item = self::constructAttachList($activity['attachments'], $item);
1361 $source = self::processElement($activity, 'source', 'content', 'mediaType', 'text/bbcode');
1362 if (!empty($source)) {
1363 $item['body'] = $source;
1366 $item['protocol'] = Conversation::PARCEL_ACTIVITYPUB;
1367 $item['source'] = $body;
1368 $item['conversation-uri'] = $activity['conversation'];
1370 foreach ($activity['receiver'] as $receiver) {
1371 $item['uid'] = $receiver;
1372 $item['contact-id'] = Contact::getIdForURL($activity['author'], $receiver, true);
1374 if (($receiver != 0) && empty($item['contact-id'])) {
1375 $item['contact-id'] = Contact::getIdForURL($activity['author'], 0, true);
1378 $item_id = Item::insert($item);
1379 logger('Storing for user ' . $item['uid'] . ': ' . $item_id);
1383 private static function fetchMissingActivity($url, $child)
1385 $object = ActivityPub::fetchContent($url);
1386 if (empty($object)) {
1387 logger('Activity ' . $url . ' was not fetchable, aborting.');
1392 $activity['@context'] = $object['@context'];
1393 unset($object['@context']);
1394 $activity['id'] = $object['id'];
1395 $activity['to'] = defaults($object, 'to', []);
1396 $activity['cc'] = defaults($object, 'cc', []);
1397 $activity['actor'] = $child['author'];
1398 $activity['object'] = $object;
1399 $activity['published'] = $object['published'];
1400 $activity['type'] = 'Create';
1401 self::processActivity($activity);
1402 logger('Activity ' . $url . ' had been fetched and processed.');
1405 private static function getUserOfObject($object)
1407 $self = DBA::selectFirst('contact', ['uid'], ['nurl' => normalise_link($object), 'self' => true]);
1408 if (!DBA::isResult($self)) {
1411 return $self['uid'];
1415 private static function followUser($activity)
1417 $uid = self::getUserOfObject($activity['object']);
1422 $owner = User::getOwnerDataById($uid);
1424 $cid = Contact::getIdForURL($activity['owner'], $uid);
1426 $contact = DBA::selectFirst('contact', [], ['id' => $cid]);
1431 $item = ['author-id' => Contact::getIdForURL($activity['owner']),
1432 'author-link' => $activity['owner']];
1434 Contact::addRelationship($owner, $contact, $item);
1435 $cid = Contact::getIdForURL($activity['owner'], $uid);
1440 $contact = DBA::selectFirst('contact', ['network'], ['id' => $cid]);
1441 if ($contact['network'] != Protocol::ACTIVITYPUB) {
1442 Contact::updateFromProbe($cid, Protocol::ACTIVITYPUB);
1445 DBA::update('contact', ['hub-verify' => $activity['id']], ['id' => $cid]);
1446 logger('Follow user ' . $uid . ' from contact ' . $cid . ' with id ' . $activity['id']);
1449 private static function acceptFollowUser($activity)
1451 $uid = self::getUserOfObject($activity['object']);
1456 $owner = User::getOwnerDataById($uid);
1458 $cid = Contact::getIdForURL($activity['owner'], $uid);
1460 logger('No contact found for ' . $activity['owner'], LOGGER_DEBUG);
1464 $fields = ['pending' => false];
1466 $contact = DBA::selectFirst('contact', ['rel'], ['id' => $cid]);
1467 if ($contact['rel'] == Contact::FOLLOWER) {
1468 $fields['rel'] = Contact::FRIEND;
1471 $condition = ['id' => $cid];
1472 DBA::update('contact', $fields, $condition);
1473 logger('Accept contact request from contact ' . $cid . ' for user ' . $uid, LOGGER_DEBUG);
1476 private static function undoFollowUser($activity)
1478 $uid = self::getUserOfObject($activity['object']);
1483 $owner = User::getOwnerDataById($uid);
1485 $cid = Contact::getIdForURL($activity['owner'], $uid);
1487 logger('No contact found for ' . $activity['owner'], LOGGER_DEBUG);
1491 $contact = DBA::selectFirst('contact', [], ['id' => $cid]);
1492 if (!DBA::isResult($contact)) {
1496 Contact::removeFollower($owner, $contact);
1497 logger('Undo following request from contact ' . $cid . ' for user ' . $uid, LOGGER_DEBUG);